Lord MagnusMardak Lord MagnusMardak - 1 year ago 131
Python Question

How to compress a text file?

I have a text file created and I want to compress it.

How would I accomplish this?

I have done some research, around the forum ; found a question, similar to this but when I tried it out, it did not work as it was text typed in, not a file, for example

import zlib, base64
code = base64.b64encode(zlib.compress(text,9))
print code

source from: (Compressing a file in python and keep the grammar exact when opening it again)

When i tried it out this error came up, for example:

hTraceback (most recent call last):
File "C:\Users\Shahid\Desktop\Suhail\Task 3.py", line 3, in <module>
code = base64.b64encode(zlib.compress(text,9))
TypeError: must be string or read-only buffer, not file

Here is the code that I have used:

import zlib, base64
text = open('Suitable.txt','r')
code = base64.b64encode(zlib.compress(text,9))
print code

But what i want is a text file to be compressed.

Answer Source

there is a section entitled "Example of how to GZIP compress an existing file" at the bottom of https://docs.python.org/2/library/gzip.html

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download