简体   繁体   中英

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.

https://docs.python.org/2/library/gzip.html底部有一个标题为“如何GZIP压缩现有文件的示例”的部分

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM