tarfile模块的主要作用是用来加压缩和解压缩文件,其压缩文件的类型可以是
.tar | .tar.gz | .tgz | .tar.bz2 等
import os import tarfile
加压:
tar = tarfile.open("/tmp/test.tar.gz","w:gz") for root,dir,files in os.walk("/home/red/桌面/test"):
for file in files: apath = os.path.join(root,file) tar.add(apath) tar.close
解压:
tar = tarfile.open("/tmp/test.tar.gz","r") for ti in tar: tar.extract(ti,"/") tar.close()
除了“w:gz","r"外,tarfile的打开模式还有好几种,如:
"w" | "w:" | "w:bz2" | "r:" | "r:gz"等
时间: 2024-10-09 17:18:13