Python:为流式写入创建压缩的tar文件

Mor*_*rse 6 python file-io gzip tar

我需要生成tar.gzipped文本文件.有没有办法为常量写入创建文件(能够做类似的事情compressedFile.write("some text")),或者我是否需要先创建原始文本文件,然后再压缩它?

这将是非常不幸的,因为文件应该非常长并且可以很好地压缩.

sam*_*ias 5

以下是如何从Python脚本编写压缩tarfile的示例:

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()
Run Code Online (Sandbox Code Playgroud)

结果:

% tar tvf example.tar.gz
-rw-r--r--  0 pat    users       17 Dec 31  1969 foo.txt
Run Code Online (Sandbox Code Playgroud)

  • 经过一些修改后工作正常。第一:`tar.tarinfo()` 不起作用,只有`tar.TarInfo()`(可能是python 的旧版本)。其次是技巧:如果你修改它,你需要在 `addfile` 之前做 `data.seek(0)`。找到这个是一个真正的挑战。谢谢! (2认同)