pythonzipcompressionpython-moduletxt

How to zip a file in python?


I have been trying to make a python script to zip a file with the zipfile module. Although the text file is made into a zip file, It doesn't seem to be compressing it; testtext.txt is 1024KB whilst testtext.zip (The code's creation) is also equal to 1024KB. However, if I compress testtext.txt manually in File Explorer, the resulting zip file is compressed (To 2KB, specifically). How, if possible, can I combat this logical error?

Below is the script that I have used to (unsuccessfully) zip a text file.

from zipfile import ZipFile

textFile = ZipFile("compressedtextstuff.zip", "w")
textFile.write("testtext.txt")
textFile.close()

Solution

  • Well that's odd. Python's zipfile defaults to the stored compression method, which does not compress! (Why would they do that?)

    You need to specify a compression method. Use ZIP_DEFLATED, which is the most widely supported.

    import zipfile
    zip = zipfile.ZipFile("stuff.zip", "w", zipfile.ZIP_DEFLATED)
    zip.write("test.txt")
    zip.close()