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