歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python zip壓縮及解壓

Python zip壓縮及解壓

日期:2017/3/1 9:53:26   编辑:Linux編程

zipfile模塊簡介
zipfile模塊() 用於壓縮文件成zip及解壓zip文件,模塊介紹如下。
·zipfile.ZipFile(file, mode) open a ZIP file,where file can be either a path to a file or a file-like object. mode can be read “r” , write “w”, or append “a”以某種模式打開ZIP 文檔. 默認值為’r’ 表示讀已經存在的zip文件,‘w’ 表示新建一個zip文檔或覆蓋一個存在的同名zip文檔, ‘a’ 表示將數據附加到一個現存的zip文檔中。

在 class zipfile.ZipFile的裡面有如下模塊:
·ZipFile.namelist() return a list of archive members by name. 返回一個列表包含zipfile裡面的文件
·ZipFile.close() close the archive file。當解壓完zip文件以後關閉zipfile.
·ZipFile.extractall(self, path=None, members=None, pwd=None) Extract all members from the archive to the current working directory. Path specified a different directory to extract to. Member is optional and must be subset of the list returned by namelist().
解壓全部文件到當前路徑,也可以加壓到指定路徑。
·ZipFile.extract(self, member, path=None, pwd=None) extract a member from the archive to the current working directory, member must be its full name. 從ZIP文件裡解壓一個文件到當前路徑,該文件必須以全名給定。
·ZipFile.setpassword(pwd) set pwd as default password to extract encrypted files. 設置一個默認密碼用於解壓文件。
·ZipFile.write(filename) write the file named filename to the archive. 將文件寫入zip文檔。


代碼:
·壓縮文件成zip包
import zipfile
import sys
import os
filepath = sys.argv[1]
outputpath = sys.argv[2]
os.chdir(filepath)
filelist = os.listdir(filepath) # list the files need to achieve
zipfilename = filepath.split("/")[-1] #fetch the last name of path as zipfile name
ZipFileobj = zipfile.ZipFile(filepath+"/"+ zipfilename +".zip", 'w') #create a zip file

for files in filelist:# use “for” to add files into zip file
ZipFileobj.write(files)

ZipFileobj.close()
print "zipfile already created!"
·解壓zip包
import zipfile
import sys

zipfilepath = sys.argv[1]
outputpath = sys.argv[2]
print zipfilepath

zipfiles = zipfile.ZipFile(zipfilepath, "r")
zipfiles.extractall(outputpath)
zipfiles.close()

相關閱讀:Python 3.2 實現zip壓縮與解壓縮功能 http://www.linuxidc.com/Linux/2011-06/37003.htm

Copyright © Linux教程網 All Rights Reserved