Test for ZIP
file
Use zipfile.is_zipfile
import zipfile
print(zipfile.is_zipfile('samples/archive.zip'))
True
Read ZIP
information
ZipFile
can manipulte ZIP
directly, for read, write or update.
Get file information
List all files archived in zip file. Use namelist
and infolist
method and get list of filenames or 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
Retrive data read()
Use read()
, fed it with filename as param, return as a 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'
Unzip file 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
Compress data
Create new zip
file. Create a new ZipFile
, use w
mode and use write()
method if you want to add file.
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() # remember to close
creating archive
adding readme.txt
closing
But by default, it just wrap all files together, not compressing it. If you want compress data, use zlib
module. And you can change the default compression mode from zipfile.ZIP_STORED
to 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