【问题标题】:Python: create a compressed tar file for streamed writingPython:创建用于流式写入的压缩 tar 文件
【发布时间】:2011-04-15 17:25:47
【问题描述】:

我需要生成 tar.gzipped 文本文件。有没有办法创建一个用于持续写入的文件(能够执行compressedFile.write("some text") 之类的操作),还是我需要先创建一个原始文本文件,然后再压缩它?

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

【问题讨论】:

  • 您是指 gzip 压缩文件而不是 tar 文件吗?
  • 我的意思是somefile.tar.gz里面应该只有一个名为somefile的文件
  • 您似乎不需要对其进行 tar,因为只有一个文件。 gzip 就足够了。
  • 这不是我为程序设计输入格式的人,我应该将这个生成的文件提供给该程序,所以我确实需要 tar :)
  • 对于不需要压缩gzip流的人,只需使用gzip模块:docs.python.org/2/library/gzip.html#module-gzip

标签: python file-io gzip tar


【解决方案1】:

这是一个如何从 Python 脚本编写压缩 tar 文件的示例:

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)。找到这个是一个真正的挑战。谢谢!
猜你喜欢
  • 2011-01-03
  • 2011-03-21
  • 1970-01-01
  • 2016-02-20
  • 1970-01-01
  • 2019-06-14
  • 2018-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多