Code tells all:
一、zipimportos,zipfile
#打包目录为zip文件(未压缩)
defmake_zip(source_dir,output_filename):
zipf=zipfile.ZipFile(output_filename,'w')
pre_len=len(os.path.dirname(source_dir))
forparent,dirnames,filenamesinos.walk(source_dir):
forfilenameinfilenames:
pathfile=os.path.join(parent,filename)
arcname=pathfile[pre_len:].strip(os.path.sep)#相对路径
zipf.write(pathfile,arcname)
zipf.close()
二、tar/tar.gzimportos,tarfile
#一次性打包整个根目录。空子目录会被打包。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
defmake_targz(output_filename,source_dir):
withtarfile.open(output_filename,"w:gz")astar:
tar.add(source_dir,arcname=os.path.basename(source_dir))
#逐个添加文件打包,未打包空子目录。可过滤文件。
#如果只打包不压缩,将"w:gz"参数改为"w:"或"w"即可。
defmake_targz_one_by_one(output_filename,source_dir):
tar=tarfile.open(output_filename,"w:gz")
forroot,dir,filesinos.walk(source_dir):
forfileinfiles:
pathfile=os.path.join(root,file)
tar.add(pathfile)
tar.close()
如果觉得《python 打包文件夹_Python打包文件夹(zip/tar/》对你有帮助,请点赞、收藏,并留下你的观点哦!