【Python压缩文件夹】导入“zipfile”模块
1 def zip_ya(startdir,file_news): 2 startdir = ".\\123" #要压缩的文件夹路径 3 file_news = startdir +‘.zip‘ # 压缩后文件夹的名字 4 z = zipfile.ZipFile(file_news,‘w‘,zipfile.ZIP_DEFLATED) #参数一:文件夹名 5 for dirpath, dirnames, filenames in os.walk(startdir): 6 fpath = dirpath.replace(startdir,‘‘) #这一句很重要,不replace的话,就从根目录开始复制 7 fpath = fpath and fpath + os.sep or ‘‘#这句话理解我也点郁闷,实现当前文件夹以及包含的所有文件的压缩 8 for filename in filenames: 9 z.write(os.path.join(dirpath, filename),fpath+filename) 10 print (‘压缩成功‘) 11 z.close() 12 13 if__name__=="__main__" 14 startdir = ".\\123" #要压缩的文件夹路径 15 file_news = startdir +‘.zip‘ # 压缩后文件夹的名字 16 zip_ya(startdir,file_news)
【python压缩文件】导入“zipfile”模块
import zipfile def zip_files( files, zip_name ): zip = zipfile.ZipFile( zip_name, ‘w‘, zipfile.ZIP_DEFLATED ) for file in files: print (‘compressing‘, file) zip.write( file ) zip.close() print (‘compressing finished‘) files = [‘.\\123.txt‘,‘.\\3.txt‘]#文件的位置,多个文件用“,”隔开 zip_file = ‘.\\m66y.zip‘#压缩包名字 zip_files(files, zip_file)