内存中的python tarfile递归提取

标签 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) # Pull out the file
  t = tarfile.open(Bundle, "r:gz") # Unpack tar
  for tItem in t:
  ...

谢谢。

最佳答案

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

import tarfile

filename = "archive.tar.gz"

with tarfile.open(filename, "r:gz") as file:
    # don't use file.members as it's 
    # not giving nested files and folders
    for member in file:
        # 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()

关于内存中的python tarfile递归提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33829591/

相关文章:

python - numba 不并行化范围

python - 循环引用的对象没有被垃圾收集

python - 在 wtform 提交上更新 SQLAlchemy 记录

Python Dataset Class + PyTorch Dataloader : Stuck at __getitem__, 测试时如何获取索引、标签等?

java - 检查两个字符串是否与字母、数字和特殊字符匹配

python - 使用盐在 SHA512 中进行散列? - Python

python - 最大矩形算法实现

python - 如何在 Python 3.3 中加密/解密字典?

python - 用 Pandas 创建空的 csv 文件

python - 有没有办法按照定义的顺序获取 argparse 的参数?