Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python文件在内存中的递归提取_Python - Fatal编程技术网

python文件在内存中的递归提取

python文件在内存中的递归提取,python,Python,我有一个包含压缩tar文件的tar文件。像这样: gnomeAware@devserv:~$ tar tf test.tar File1.tar.gz File2.tar.gz File3.tar.gz File4.tar.gz tarfile需要一个字符串作为要打开的文件。是否仍要向其传递文件对象 tar = tarfile.open('test.tar', 'r') # Unpack tar for item in tar: Bundle=tar.extractfile(item) #

我有一个包含压缩tar文件的tar文件。像这样:

gnomeAware@devserv:~$ tar tf test.tar
File1.tar.gz
File2.tar.gz
File3.tar.gz
File4.tar.gz
tarfile需要一个字符串作为要打开的文件。是否仍要向其传递文件对象

tar = tarfile.open('test.tar', 'r') # Unpack tar
for item in tar:
  Bundle=tar.extractfile(item) # Pull out the file
  t = tarfile.open(Bundle, "r:gz") # Unpack tar
  for tItem in t:
  ...

谢谢。

tarfile.open的定义如下所示
def open(cls,name=None,mode=“r”,fileobj=None,bufsize=RECORDSIZE,**kwargs):

python说

如果指定了fileobj,它将用作为name打开的文件对象的替代项。它应该位于位置0

因此,您可以使用关键字参数来调用它,而不是使用位置参数来调用它。传递fileobj而不是名称

import tarfile

f = open('archive.tar', 'rb')
print (f)
tar = tarfile.open(fileobj=f, mode='r:') # Unpack tar
for item in tar:
    print(item)

以下是读取存档中每个文件数据的方法:

import tarfile

filename = "archive.tar.gz"

with tarfile.open(filename, "r:gz") as file:
    for member in file.members:
        # You need additional code to save the data into a list.
        file_content_byte = file.extractfile(member.name).read()
如果您已经知道存档中文件的名称,则可以执行以下操作:

import tarfile

filename = "archive.tar.gz"

with tarfile.open(filename, "r:gz") as file:
    file_content_byte = file.extractfile("file.txt").read()
From:“如果指定了fileobj,它将用作以二进制模式打开的文件对象的替代名称。它应该位于位置0。”
tar.extractfile(fileobj=Bundle,mode=“r:gz”)