Python’s ‘zipfile’ Module
July 8, 2010 Comments
I was writing some scripts today and part of it is to compress some files. I normally make an external application call to 7-Zip command line when I do this, but then I decided to just do a quick Google search to see if Python has one built in.
It turned out there’s this zipfile module that’s part of the standard library that can compress and decompress files for you (only the standard ZIP compression method is supported).
Here are a couple examples:
Zipping a File
import zipfile sourceFile = r"C:\ziptest\testfile.txt" outputFile = r"C:\ziptest\testfile.zip" try: zipper = zipfile.ZipFile(outputFile, "w", zipfile.ZIP_DEFLATED) zipper.write(sourceFile) except zipfile.BadZipfile as zipfileException: print zipfileException finally: zipper.close()
Unzipping a File
import zipfile sourceFile = r"C:\ziptest\testfile.zip" outputFolder = r"C:\ziptest\unzipped" try: unzipper = zipfile.ZipFile(sourceFile) unzipper.extractall(outputFolder) except zipfile.BadZipfile as zipfileException: print zipfileException finally: unzipper.close()