python - 添加到 tarfile 的文件返回为空文件

标签 python

我正在尝试将文件添加到 python 中的 gzipped tarfile

import tarfile

# create test file
with open("testfile.txt", "w") as f:
    f.write("TESTTESTTEST")

# create archive
with tarfile.open("archfile.tar.gz", "x:gz") as archive:
    with open("testfile.txt", 'rb') as f:
        archive.addfile(tarfile.TarInfo("testfile.txt"), f)

# read test file out of archive
with tarfile.open("archfile.tar.gz", "r:gz") as archive:
    print(archive.extractfile("testfile.txt").read())

结果是 b'' - 一个空字节串。

文件不为空 - 如果我尝试使用以下代码读取文件:

with open("testfile.txt", 'rb') as f:
    print(f.read())

...我得到b'TESTTESTTEST'

我是否遗漏了一些明显的东西?我的最终目标是使用 f = io.StringIO('TESTTESTTEST')

将字符串添加到内存中

我还尝试删除 :gz 并且我发现原始 tar 存档也存在同样的问题。

有关更多信息 - 我在 Windows 10 上的 jupyter session 中使用 Python 3。我在 Windows/Python 3.5.2/PyCharm 中看到同样的问题。

最佳答案

我遇到了类似的问题。文档说,当您调用 tar.addfile 时,它将从给定文件写入 TarInfo.size 字节。这意味着您必须使用文件大小创建 TarInfo 或使用 tar.add() 而不是 tar.addfile:

# create archive V1
with tarfile.open("archfile.tar.gz", "x:gz") as archive:
    with open("testfile.txt", 'rb') as f:
        info = archive.gettarinfo("testfile.txt")
        archive.addfile(info, f)

# create archive V2
with tarfile.open("archfile.tar.gz", "x:gz") as archive:
    archive.add("testfile.txt")

# create archive V3
with tarfile.open("archfile.tar.gz", "w:gz") as archive:
    with io.BytesIO(b"TESTTESTTEST") as f:
        info = tarfile.TarInfo("testfile.txt")
        f.seek(0, io.SEEK_END)
        info.size = f.tell()
        f.seek(0, io.SEEK_SET)
        archive.addfile(info, f)

关于python - 添加到 tarfile 的文件返回为空文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48461065/

相关文章:

python capitalize() 在以空格开头的字符串上

python - 在 Python 的 try block 中使用 finally 的实际例子是什么

python - 在 Python 中使用 pprint.pprint 后,我​​可以避免排序字典输出吗?

python - 在 Numpy 中将一维数组添加到三维数组

python - 使用对数刻度注释 seaborn distplot 会引发错误

python - 更改 DataFrame 最后一行中的元素

Python 实例化模块中的所有类

python - 为什么 list_a = list_a.append(1) 会产生 NoneType 而不是通过错误?

python - 基于语言测试的阿拉伯语句子过滤列表 : Why so slow?

python - 如何在Python中存储目标词