python - 如何使用 python tarfile 模块将文件附加到 tar 文件?

标签 python tarfile

我想将文件附加到 tar 文件。例如test.tar.gz中的文件是a.png, b.png, c.png。我有一个名为 a.png 的新 png 文件,我想将 a.png 附加到 test.tar.gz 并覆盖旧文件test.tar.gz 中的文件 a.png。我的代码:

import tarfile
a = tarfile.open('test.tar.gz', 'w:gz')
a.add('a.png')
a.close()

然后,test.tar.gz 中的所有文件都消失了,但是 a.png,如果我将代码更改为:

import tarfile
a = tarfile.open('test.tar.gz', 'a:')# or a:gz
a.add('a.png')
a.close()

程序崩溃,错误日志:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/tarfile.py", line 1678, in open
    return func(name, filemode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1705, in taropen
    return cls(name, mode, fileobj, **kwargs)
  File "/usr/lib/python2.7/tarfile.py", line 1588, in __init__
    raise ReadError(str(e))
tarfile.ReadError: invalid header

我的错误是什么,我该怎么办?

更新。从文档中可以看出,gz 文件无法在 a 模式下打开。如果是这样,在现有存档中添加或更新文件的最佳方式是什么?

最佳答案

来自 tarfile documentation :

Note that 'a:gz' or 'a:bz2' is not possible. If mode is not suitable to open a certain (compressed) file for reading, ReadError is raised. Use mode 'r' to avoid this. If a compression method is not supported, CompressionError is raised.

所以我想你应该使用 gzip library 解压缩它,在tarfile中使用a:模式添加文件,然后使用gzip再次压缩。

关于python - 如何使用 python tarfile 模块将文件附加到 tar 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28361665/

相关文章:

python - 在 Python 中将文件添加到 Tar 内的空目录

python - 如何从python中的.tar存档中提取特定文件?

python - 当滚动条已设置时更新 WheelEvent 上的 QLineEdit

python - 如何在 Django 中为模型设置默认值?

python - 通过另一个 DataFrame 的索引选择某些行

python - 使用 Python 的 tarfile 创建 tarball 时保留文件权限

python - 使用 matplotlib savefig 保存文件对象,从多个 svg 图形创建 tar 文件

Emacs 中的 Python(无模式,普通安装)

python - elasticsearch 聚合哈希值的唯一条目并查找所有标签

python - 为什么 tarfile 模块不允许压缩 append ?