如何使用python tarfile模块将文件附加到tar文件? [英] How to append a file to a tar file use python tarfile module?
问题描述
我想将一个文件附加到tar文件中.例如,test.tar.gz
中的文件是a.png, b.png, c.png
.我有一个名为a.png
的新png文件,我想将a.png
附加到test.tar.gz
,并覆盖test.tar.gz
中的旧文件a.png
.我的代码:
I want to append a file to the tar file. For example, the files in test.tar.gz
are a.png, b.png, c.png
. I have a new png file named a.png
, I want to append to a.png
to test.tar.gz
and cover the old file a.png
in test.tar.gz
. My code:
import tarfile
a = tarfile.open('test.tar.gz', 'w:gz')
a.add('a.png')
a.close()
然后,如果我将代码更改为此,test.tar.gz
中的所有文件都消失了,但a.png
消失了:
then, all the files in test.tar.gz
disappeard but a.png
, if I change my code to this:
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
我的错误是什么,我该怎么办?
What are my mistakes and what should I do?
更新.根据文档,无法在a
模式下打开gz
文件.如果是这样,在现有存档中添加或更新文件的最佳方法是什么?
Update. From the documentation, it follows that gz
files cannot be open in a
mode. If so, what is the best way to add or update files in an existing archive?
推荐答案
来自 tarfile
文档:
请注意,不能使用
'a:gz'
或'a:bz2'
.如果mode不适合打开某个(压缩的)文件进行读取,则会引发ReadError
.使用模式"r"可以避免这种情况.如果不支持压缩方法,则会引发CompressionError
.
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
库将其解压缩,添加在tarfile
中以a:
模式使用文件,然后使用gzip
再次压缩.
So I guess you should decompress it using gzip
library, add the files using the a:
mode in tarfile
, and then compress again using gzip
.
这篇关于如何使用python tarfile模块将文件附加到tar文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!