Python压缩文件夹 tar.gz .zip
打包压缩生成 XXX.tar.gz 文件
1 import os 2 import tarfile 3 4 if os.path.exists(outputFileName): 5 with tarfile.open(outputFileName + ".tar.gz", "w:gz") as tar: 6 tar.add(sourceDir, arcname=os.path.basename(sourceDir))
open的原型是:
1 tarfile.open(name=None, mode='r', fileobj=None, bufsize=10240, **kwargs)
tarfile.open的mode有很多种:
'r' or 'r:*' | Open for reading with transparent compression (recommended). |
'r:' | Open for reading exclusively without compression. |
'r:gz' | Open for reading with gzip compression. |
'r:bz2' | Open for reading with bzip2 compression. |
'a' or 'a:' | Open for appending with no compression. The file is created if it does not exist. |
'w' or 'w:' | Open for uncompressed writing. |
'w:gz' | Open for gzip compressed writing. |
'w:bz2' | Open for bzip2 compressed writing. |
在写打包代码的过程中,使用tar.add()增加文件时,会把文件本身的路径也加进去,加上arcname就能根据自己的命名规则将文件加入tar包
打包压缩生成 XXX.zip 文件
1 import os 2 import zipfile 3 4 zip_file = zipfile.ZipFile(report_path + ".zip", "w", zipfile.ZIP_DEFLATED) 5 for dirpath, dirnames, filenames in os.walk(report_path): # report_path是要压缩的文件夹 6 fpath = dirpath.replace(report_path, '') 7 fpath = fpath and fpath + os.sep or "" 8 for filename in filenames: 9 zip_file.write(os.path.join(dirpath, filename), fpath + filename) # 只能一个文件一个文件地往里写 10 zip_file.close()