簡體   English   中英

Python:為流式寫入創建壓縮的tar文件

[英]Python: create a compressed tar file for streamed writing

我需要生成tar.gzipped文本文件。 有沒有辦法為常量寫入創建文件(能夠執行像compressedFile.write("some text") ),或者我是否需要先創建原始文本文件,然后再壓縮它?

這將是非常不幸的,因為文件應該非常長並且可以很好地壓縮。

以下是如何從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()

結果:

% tar tvf example.tar.gz
-rw-r--r--  0 pat    users       17 Dec 31  1969 foo.txt

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM