我想将文件附加到 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
模式下打开。如果是这样,在现有存档中添加或更新文件的最佳方式是什么?
最佳答案
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/