一旦我在特定文件夹中拥有了我需要的所有文件,我希望我的python脚本压缩文件夹内容.
这可能吗?
我怎么能这样做呢?
在python 2.7上你可以使用:shutil.make_archive(base_name,format [,root_dir [,base_dir [,verbose [,dry_run [,owner [,group [,logger]]]]]]]).
base_name存档名称减去扩展名
存档的格式格式
要压缩的root_dir目录.
例如
shutil.make_archive(target_file, format="bztar", root_dir=compress_me)
脚本的改编版本是:
#!/usr/bin/env python from __future__ import with_statement from contextlib import closing from zipfile import ZipFile, ZIP_DEFLATED import os def zipdir(basedir, archivename): assert os.path.isdir(basedir) with closing(ZipFile(archivename, "w", ZIP_DEFLATED)) as z: for root, dirs, files in os.walk(basedir): #NOTE: ignore empty directories for fn in files: absfn = os.path.join(root, fn) zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path z.write(absfn, zfn) if __name__ == '__main__': import sys basedir = sys.argv[1] archivename = sys.argv[2] zipdir(basedir, archivename)
例:
C:\zipdir> python -mzipdir c:\tmp\test test.zip
它'C:\zipdir\test.zip'
使用'c:\tmp\test'
目录的内容创建存档.
这是一个递归版本
def zipfolder(path, relname, archive): paths = os.listdir(path) for p in paths: p1 = os.path.join(path, p) p2 = os.path.join(relname, p) if os.path.isdir(p1): zipfolder(p1, p2, archive) else: archive.write(p1, p2) def create_zip(path, relname, archname): archive = zipfile.ZipFile(archname, "w", zipfile.ZIP_DEFLATED) if os.path.isdir(path): zipfolder(path, relname, archive) else: archive.write(path, relname) archive.close()