提取内存文件系统中的Tar文件

问题描述 投票:1回答:1

我在使用memoryfs时遇到问题:https://docs.pyfilesystem.org/en/latest/reference/memoryfs.html

我正在尝试在memoryFS中提取tar,但是我不能使用mem_fs,因为它是一个对象,无法获取真实的/内存路径...

from fs import open_fs, copy
import fs
import tarfile

mem_fs = open_fs('mem://')

print(mem_fs.isempty('.'))

fs.copy.copy_file('//TEST_FS', 'test.tar', mem_fs, 'test.tar')

print(mem_fs.listdir('/'))

with mem_fs.open('test.tar') as tar_file:
    print(tar_file.read())
    tar = tarfile.open(tar_file) // I cant create the tar ...
    tar.extractall(mem_fs + 'Extract_Dir') // Cant extract it too...

有人可以帮我,有可能吗?

python memory tar fs
1个回答
0
投票

tarfile.open的第一个参数是文件名。您(a)向其传递了一个打开的文件对象,并且(b)即使您要传递文件名,tarfile对内存文件系统一无所知,因此无法找到文件。

幸运的是,tarfile.open具有接受打开文件对象的fileobj参数,因此您可以编写:

with mem_fs.open('test.tar', 'rb') as tar_file:
    tar = tarfile.open(None, tar_file)
    t.list()

注意,您需要以二进制模式(rb)打开文件。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.