Lord MagnusMardak
Lord MagnusMardak

Reputation: 41

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
text = 'STACK OVERFLOW'
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.

Upvotes: 0

Views: 16546

Answers (2)

ands
ands

Reputation: 2036

you should use this code to do what you tried:

import zlib, base64
file = open('Suitable.txt','r')
text = file.read()
file.close()
code =  base64.b64encode(zlib.compress(text.encode('utf-8'),9))
code = code.decode('utf-8')
print(code)

but it actually want be compressed because code is longer than text.

Upvotes: 0

Chris Curvey
Chris Curvey

Reputation: 10389

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

Upvotes: 2

Related Questions