Python: zipfile壓縮解壓檔案
阿新 • • 發佈:2019-02-14
判斷是否是ZIP
檔案
用zipfile.is_zipfile
判斷。
import zipfile
print(zipfile.is_zipfile('samples/archive.zip'))
True
ZipFile
可以直接操作ZIP
,支援讀取資料以及對其修改。
讀取檔案資訊
List
出來archive檔案裡內容,用namelist 和 infolist方法。返回list of filenames
或list of ZipInfo instances
。
import zipfile
zf = zipfile.ZipFile('samples/archive.zip' ,'r')
# list filenames
for name in zf.namelist():
print name,
a.txt b.txt c.txt
# list file infomation
for info in zf.infolist():
print info.filename, info.date_time, info.file_size
a.txt (2016, 7, 15, 0, 5, 58) 2
b.txt (2016, 7, 15, 0, 6, 8) 2
c.txt (2016, 7, 15, 0, 6, 14) 2
提取資料read()
用read()
方法,以filename
作為引數,以string
形式返回資料。
zf = zipfile.ZipFile('samples/archive.zip')
for filename in zf.namelist():
# can use other than namelist,['there.txt','notthere.txt']
try:
data = zf.read(filename) # extract use read()
except KeyError:
print "Error: Did not find %s in zip file" % filename
else:
print filename, ':',
print repr(data)
a.txt : 'a\n'
b.txt : 'b\n'
c.txt : 'c\n'
解壓資料extract()
zf = zipfile.ZipFile('samples/archive.zip','r')
# Extract a member from the archive to the current working directory
zf.extract('a.txt') # you may want to specify path param
# Extract all members from the archive to the current working directory
zf.extractall() # you may want to specify path param
壓縮資料
建立新的zip
檔案,只需要初始化一個新的ZipFile
即可,用w
模式,要新增資料,用write()
方法即可。
print('creating archive')
zf = zipfile.ZipFile('zipfile_write.zip',mode='w')
try:
print('adding readme.txt')
zf.write('readme.txt')
finally:
print('closing')
zf.close()
creating archive
adding readme.txt
closing
但是預設沒有隻是打包,沒有壓縮資料,如果壓縮,需要用zlib
模組。預設壓縮模式zipfile.ZIP_STORED
,可以改變為zipfile.ZIP_DEFLATED
。
# try to change compression type
try:
import zlib
compression = zipfile.ZIP_DEFLATED
except:
compression = zipfile.ZIP_STORED
modes = {zipfile.ZIP_DEFLATED: 'deflated', zipfile.ZIP_STORED: 'stored'}
print('creating archive')
zf = zipfile.ZipFile('zipfile_write_compression.zip',mode='w')
try:
print('adding README.txt with compression mode'+ str(modes[compression]))
zf.write('readme.txt',compress_type=compression)
finally:
print('closing')
zf.close()
creating archive
adding README.txt with compression modedeflated
closing