'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 1:[1]
In the docs they have it written with a with statement so I would try that first.
Edit:
I just came back to say that you have to specify your compression method but Mark beat me to the punch.
Here is a link to a StackOverflow post about it https://stackoverflow.com/questions/4166447/python-zipfile-module-doesnt-seem-to-be-compressing-my-files#:~:text=This%20is%20because%20ZipFile%20requires,the%20method%20to%20be%20zipfile.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
