python zip压缩_Python zip压缩与解压(zipfile模块实例)
python中提供了文件壓縮的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文檔。
例1,壓縮文件成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!"
例2,解壓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 zip压缩_Python zip压缩与解压(zipfile模块实例)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jquery中ajax完整例子get,j
- 下一篇: python文件替换一行_python自