1. 程式人生 > 程式設計 >Python中zipfile壓縮檔案模組的基本使用教程

Python中zipfile壓縮檔案模組的基本使用教程

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 檔案了

Python中zipfile壓縮檔案模組的基本使用教程

向已存在的壓縮檔案中追加內容

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那一級的目錄。

Python中zipfile壓縮檔案模組的基本使用教程

解壓檔案

將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壓縮檔案模組的基本使用教程的文章就介紹到這了,更多相關Python zipfile壓縮檔案模組使用內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!