GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Monday, March 21, 2011

Python - ZipFile

To list the file name contains in a zip file, type:
>>> import zipfile
>>> f = zipfile.ZipFile('hello.zip', '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 = f.read(file_name[2]);

To create a zip archive, you need to type
>>> f = zipfile.ZipFile('hello.zip', '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('hello.zip', '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)
Share/Bookmark

No comments:

Post a Comment