Monday, March 21, 2011

Python - ZipFile

To list the file name contains in a zip file, type:
>>> import zipfile
>>> f = zipfile.ZipFile('', 'r')
>>> for i in f.namelist():
        print i

To get the more info of the files contained in a zip file, type:
>>> for i in f.infolist():
        print i.filename, i.date_time, i.file_size

To read a file from an zip archive, use read method and supply a file name as its argument
>>> content =[2]);

To create a zip archive, you need to type
>>> f = zipfile.ZipFile('', 'w')
>>> f.write('source.txt', 'name_in_archive.txt', zipfile.ZIP_DEFLATED)
>>> f.write('luna.txt', 'maya.txt', zipfile.ZIP_DEFLATED)
>>> f.close()

For appending a file to an existing zip archive file, use append as mode
>>> f = zipfile.ZipFile('', 'a')
>>> f.write('lady.txt', 'gaga.txt', zipfile.ZIP_DEFLATED)
>>> f.close()

For writing a string to an zip archive, use
>>> string_data = 'This the data'
>>> info = zipfile.ZipInfo(string_data)
>>> f.writestr(info, string_data)

No comments:

Post a Comment