Work with zip file

List files in the zip file


import zipfile# www . j a  v a  2s  .  co  m
zz = zipfile.ZipFile('z.zip')
zz.printdir()
for name in zz.namelist():
    print '%s: %r' % (name, zz.read(name))
zz.close()

Loop through header information in a ZIP file


       # from   w  ww .  j a  v  a2s . c o m
import struct

data = open('myfile.zip', 'rb').read()
start = 0
for i in range(3):                      # show the first 3 file headers
    start += 14
    fields = struct.unpack('LLLHH', data[start:start+16])
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16
    filename = data[start:start+filenamesize]
    start += filenamesize
    extra = data[start:start+extra_size]
    print filename, hex(crc32), comp_size, uncomp_size

    start += extra_size + comp_size     # skip to the next header

Zip a file


# from ww w. j  a va 2 s.co m
import zipfile
def data_to_zip_direct(z, data, name):
    import time
    zinfo = zipfile.ZipInfo(name, time.localtime()[:6])
    z.writestr(zinfo, data)
def data_to_zip_indirect(z, data, name):
    import os
    flob = open(name, 'wb')
    flob.write(data)
    flob.close()
    z.write(name)
    os.unlink(name)
    
zz = zipfile.ZipFile('z.zip', 'w', zipfile.ZIP_DEFLATED)
data = 'four score\nand seven\nyears ago\n'
data_to_zip_direct(zz, data, 'direct.txt')
data_to_zip_indirect(zz, data, 'indirect.txt')
zz.close()

Multi-threading: zip file


import threading, zipfile
# from ww  w  .j a v  a  2 s  .c  om
class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)        
        self.infile = infile
        self.outfile = outfile
    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print 'Finished background zip of: ', self.infile

background = AsyncZip('mydata.txt', 'myarchive.zip')
background.start()
print 'The main program continues to run in foreground.'

background.join()    # Wait for the background task to finish
print 'Main program waited until background was done.'

Adding Files to a ZIP File


#  w  w w  .ja v a  2s.  co  m
import os
import zipfile

tFile = zipfile.ZipFile("files.zip", 'w')

files = os.listdir(".")
for f in files:
    tFile.write(f)

#List archived files
for f in tFile.namelist():
    print "Added %s" % f


tFile.close()

Retrieving Files from a ZIP File


import os# from w w  w . j av a2  s . com
import zipfile


tFile = zipfile.ZipFile("files.zip", 'r')

print tFile.getinfo("input.txt")

buffer = tFile.read("ren_file.py")
print buffer

f = open("extract.txt", "w")
f.write(buffer)
f.close()

tFile.close()




















Home »
  Python »
    Advanced Features »




Exception Handling
File
Module