Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 332
Ihavenogoddamnclue Avatar asked Aug 27 '26 16:08

Ihavenogoddamnclue


1 Answers

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()
like image 169
Mark Adler Avatar answered Aug 29 '26 06:08

Mark Adler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!