zipfile
Python 中 zipfile 模塊提供了對 zip 壓縮文件的一系列操作。
f=zipfile.ZipFile("test.zip",mode="") //解壓是 r , 壓縮是 w 追加壓縮是 a
mode的幾種:
解壓:r
壓縮:w
追加壓縮:a
壓縮一個文件
創建一個壓縮文件 test.zip(如果test.zip文件不存在) ,然後將 test.txt 文件加入到壓縮文件 test.zip 中,如果原來的壓縮文件中有內容,會清除原有的內容
import zipfile try: with zipfile.ZipFile("c://users//17250//desktop//test.zip",mode="w") as f: f.write("c://users//17250//desktop//test.txt") #寫入壓縮文件,會把壓縮文件中的原有覆蓋 except Exception as e: print("異常對象的類型是:%s"%type(e)) print("異常對象的內容是:%s"%e) finally: f.close()
如果要壓縮的文件的路徑是 c://users//17250//desktop//test.txt
這樣的話,
那麼最後壓縮文件裡面壓縮的就是 users//17250//desktop//test.txt
文件了
向已存在的壓縮文件中追加內容
import zipfile try: with zipfile.ZipFile("c://users//17250//desktop//test.zip",mode="a") as f: f.write("e://test.txt") #追加寫入壓縮文件 except Exception as e: print("異常對象的類型是:%s"%type(e)) print("異常對象的內容是:%s"%e) finally: f.close()
雖然原文件裡面壓縮的文件的路徑是 users//17250//desktop//test.txt
,但是追加進去的是 e://test2.txt
文件,那麼test2.txt 文件壓縮是在 users 那一級的目錄。
解壓文件
將test.zip文件解壓
在python3中,解壓文件的密碼參數 pwd 接收的是二進制的值,所以要在前面加一個 b 。python2中接受的是str字符串的值。
import zipfile try: with zipfile.ZipFile("c://users//17250//desktop//test.zip",mode="a") as f: f.extractall("c://users//17250//desktop//",pwd=b"root") ##將文件解壓到指定目錄,解壓密碼為root except Exception as e: print("異常對象的類型是:%s"%type(e)) print("異常對象的內容是:%s"%e) finally: f.close()
高級應用
zipfile.is_zipfile(filename)
判斷一個文件是不是壓縮文件
ZipFile.namelist()
返回文件列表
if zipfile.is_zipfile('test.zip'): #is_zipfile() 判斷是否似zip文件 f = zipfile.ZipFile('test.zip') files = f.namelist() #namelist() 返回zip壓縮包中的所有文件 print(files) f.close()
[月球人 ] Python中zipfile壓縮文件模塊的基本使用教程已經有250次圍觀