1.压缩一个文件夹下的所有文件
#coding=utf8 import os import tarfile __author__ = 'Administrator' def main(): cwd = os.getcwd() tar = tarfile.open('test.tar','w:gz') for root ,dir,files in os.walk(cwd): for file in files: fullpath = os.path.join(root,file) tar.add(fullpath) if __name__=='__main__': main()
2.解压缩一个tar包
import tarfile tar = tarfile.open("sample.tar.gz") tar.extractall() tar.close()
3.有选择的解压缩一个tar包
import os import tarfile def py_files(members): for tarinfo in members: if os.path.splitext(tarinfo.name)[1] == ".py": yield tarinfo tar = tarfile.open("sample.tar.gz") tar.extractall(members=py_files(tar)) tar.close()
参考资料:
https://docs.python.org/2/library/tarfile.html