Wednesday, March 29, 2017

Working with zipfile module Python

Memo related to zipfile module and most common methods from this module.

import zipfile

compressedFile = zipfile.ZipFile('test.zip')

compressedFile.namelist() - returns list of files and directories in archive

fileInfo = compressedFile.getinfo('file') - returns information about file in archive

fileInfo.file_size - returns size of the file

fileInfo.compress_size - returns compression ratio

compressedFile.extractall() - extracts everything from zip into current directory

compressedFile.extractall(path) - extracts everything from zip to destination directory

compressedFile.extract('file', path) - extracts exact file from zip to destination path


newZip = zipfile.ZipFile('test.zip', 'w')
newZip.write('test.txt', compress_type=zipfile.ZIP_DEFLATED)
newZip.close() - adding file to archive however this will overrides all archive

zipfile.ZipFile('test.zip', 'a') - adding file to archive without overriding 


No comments:

Post a Comment