我需要生成tar.gz压缩的文本文件。有没有一种方法可以创建一个用于常量写入的文件(以便像 compressedFile.write("some text")
这样做),还是需要先创建原始文本文件,然后再进行压缩?
这将非常不幸,因为该文件应该非常长且易于压缩。
import StringIO
import tarfile
tar = tarfile.open('example.tar.gz', 'w:gz')
# create a file record
data = StringIO.StringIO('this is some text')
info = tar.tarinfo()
info.name = 'foo.txt'
info.uname = 'pat'
info.gname = 'users'
info.size = data.len
# add the file to the tar and close it
tar.addfile(info, data)
tar.close()
结果:
% tar tvf example.tar.gz
-rw-r--r-- 0 pat users 17 Dec 31 1969 foo.txt
tar.tarinfo()
无法使用,只能使用tar.TarInfo()
(可能是Python版本太旧了)。第二个问题比较棘手:如果您对addfile
进行修改,则需要在之前执行data.seek(0)
。这真的是一个挑战才找到这个问题所在。谢谢! - Morse
somefile.tar.gz
,其中应该只有一个名为somefile
的文件。 - Morse