Python/Zip: Difference between revisions
< Python
(→pkzip) |
(No difference)
|
Latest revision as of 21:28, 23 August 2017
pkzip
Test if zip file is valid
# test if the file is a valid pkzip file if zipfile.is_zipfile(zfilename):
# Extract all: import zipfile zfile = zipfile.ZipFile( zfilename, "r" ) zfile.extractall()
# open a zip file and show information import zipfile zfile = zipfile.ZipFile( zfilename, "r" ) print "Simple file information retrieval:" zfile.printdir() zfile.close()
# read the zipped file back in ... zin = zipfile.ZipFile(zfilename, "r") strz = zin.read(arc_name) zin.close()
Show archive information:
import datetime
import zipfile
def print_info(archive_name):
zf = zipfile.ZipFile(archive_name)
for info in zf.infolist():
print info.filename
print '\tComment:\t', info.comment
print '\tModified:\t', datetime.datetime(*info.date_time)
print '\tSystem:\t\t', info.create_system, '(0 = Windows, 3 = Unix)'
print '\tZIP version:\t', info.create_version
print '\tCompressed:\t', info.compress_size, 'bytes'
print '\tUncompressed:\t', info.file_size, 'bytes'
print
if __name__ == '__main__':
print_info('example.zip')
References:
- Compress Files with Zip (Python) | DaniWeb - http://www.daniweb.com/software-development/python/code/216859/compress-files-with-zip-python
- zipfile – Read and write ZIP archive files - Python Module of the Week - http://www.doughellmann.com/PyMOTW/zipfile/
Extract
import zipfile
import os.path
zfile = zipfile.ZipFile("test.zip")
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
print "Decompressing " + filename + " on " + dirname
if not os.path.exists(dirname):
os.mkdir(dirname)
fd = open(name,"w")
fd.write(zfile.read(name))
fd.close()
My modifications:
import zipfile
import os.path
zfile = zipfile.ZipFile("test.zip")
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
print "Decompressing " + name
if dirname and not os.path.exists(dirname):
os.mkdir(dirname)
if filename:
fd = open(name,"w")
fd.write(zfile.read(name))
fd.close()
---
import os
from zipfile import ZipFile, ZipInfo
class ZipCompat(ZipFile):
def __init__(self, *args, **kwargs):
ZipFile.__init__(self, *args, **kwargs)
def extract(self, member, path=None, pwd=None):
if not isinstance(member, ZipInfo):
member = self.getinfo(member)
if path is None:
path = os.getcwd()
return self._extract_member(member, path)
def extractall(self, path=None, members=None, pwd=None):
if members is None:
members = self.namelist()
for zipinfo in members:
self.extract(zipinfo, path)
def _extract_member(self, member, targetpath):
if (targetpath[-1:] in (os.path.sep, os.path.altsep)
and len(os.path.splitdrive(targetpath)[1]) > 1):
targetpath = targetpath[:-1]
if member.filename[0] == '/':
targetpath = os.path.join(targetpath, member.filename[1:])
else:
targetpath = os.path.join(targetpath, member.filename)
targetpath = os.path.normpath(targetpath)
upperdirs = os.path.dirname(targetpath)
if upperdirs and not os.path.exists(upperdirs):
os.makedirs(upperdirs)
if member.filename[-1] == '/':
if not os.path.isdir(targetpath):
os.mkdir(targetpath)
return targetpath
target = file(targetpath, "wb")
try:
target.write(self.read(member.filename))
finally:
target.close()
return targetpath
# unzip a file
def unzip(path):
zfile = zipfile.ZipFile(path)
for name in zfile.namelist():
(dirname, filename) = os.path.split(name)
if filename == '':
# directory
if not os.path.exists(dirname):
os.mkdir(dirname)
else:
# file
fd = open(name, 'w')
fd.write(zfile.read(name))
fd.close()
zfile.close()
References:
- How to unzip a zip file with Python 2.4? - Stack Overflow - http://stackoverflow.com/questions/7806563/how-to-unzip-a-zip-file-with-python-2-4
Compress
help:
pydoc zipfile
import zipfile str1 = """There is no ham in hamburger.""" arc_name = "English101.txt" zfilename = "English101.zip" zout = zipfile.ZipFile(zfilename, "w") zout.writestr(arc_name, str1) zout.close()
# append file:
# zf = zipfile.ZipFile('zipfile_append.zip', mode='a')
zf = zipfile.ZipFile('zipfile_write.zip', mode='w')
try:
print 'adding README.txt'
zf.write('README.txt')
# alternate name:
# zf.write('README.txt', arcname='NOT_README.txt')
finally:
print 'closing'
zf.close()
WARNING: By default, the contents of the archive are not compressed! To add compression, the zlib module is required. If zlib is available, you can set the compression mode for individual files or for the archive as a whole using zipfile.ZIP_DEFLATED. The default compression mode is zipfile.ZIP_STORED.
from zipfile_infolist import print_info
import zipfile
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', modes[compression]
zf.write('README.txt', compress_type=compression)
finally:
print 'closing'
zf.close()
References:
- Compress Files with Zip (Python) | DaniWeb - http://www.daniweb.com/software-development/python/code/216859/compress-files-with-zip-python
- zipfile – Read and write ZIP archive files - Python Module of the Week - http://www.doughellmann.com/PyMOTW/zipfile/