python zipfile 壓縮zip檔案和解壓zip檔案
阿新 • • 發佈:2018-12-11
本文記錄python 利用模組zipfile實現對檔案的壓縮機解壓處理,對應日常的工作能提供很大的便利性
1:檔案壓縮成zip
author:he qq:760863706 python:3.5 date:2018-9-20
from pathlib import Path import zipfile def create_zip(dir,new_zip): #dir 待處理資料夾或檔案 #new_zip 生成目錄zip檔案 file_lists = [] # 例項 p = Path(dir) if p.is_file(): file_lists.append(p) else : # 遍歷資料夾 filelist = list(p.glob('**/*')) for file in filelist: # 獲取到的檔案新增到列表中 if Path.is_file(file):file_lists.append(file) #例項化,mode為 'w' 表示對zip檔案清空後新增,'a'表示對zip檔案追加的方式新增,allowZip64為True表示可壓縮大於2G檔案 zip = zipfile.ZipFile(new_zip,mode='w',compression=zipfile.ZIP_STORED,allowZip64=False) for filename in file_lists: #獲取檔名 arcname = Path(filename).name #windowPath轉str zip.write(str(filename),arcname) zip.close()
2:zip檔案解壓
from pathlib import Path import zipfile def unzip(zpath,to_dir): # zpath 待處理zip檔案 # to_dir 目標資料夾 # 建立目標資料夾 Path(to_dir).mkdir(parents=True, exist_ok=True) #例項化 zip = zipfile.ZipFile(zpath) #一次性全部解壓 # zip.extractall(path=to_dir) # zip.close() for file in zip.namelist(): #單次解壓 zip.extract(file,path=to_dir) zip.close()
本文模組pathlib 需要滿足python3.4以上,pathlib用起來感覺很多方面比os處理更便捷