Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 GZip Compressing String

I am trying to do the following with Python3:

data = json.dumps(packet)
s = StringIO()
g = gzip.GzipFile(fileobj=s, mode='w')
g.write(data)
g.close()
gzipped_body = s.getvalue()

But it keeps complaining with the following error:

TypeError: string argument expected, got 'bytes'

The example code I'm using is based on Python2 so I am thinking there is some changes in StringIO that might be causing this but I'm not sure. Anyone give me some hints on how to get a gzipped string of some JSON in Python3?

like image 663
Gregg Avatar asked Sep 02 '14 20:09

Gregg


People also ask

How do I compress a string to gzip?

With the help of gzip. compress(s) method, we can get compress the bytes of string by using gzip. compress(s) method. Return : Return compressed string.

How do you compress and decompress a string in Python?

With the help of gzip. decompress(s) method, we can decompress the compressed bytes of string into original string by using gzip. decompress(s) method. Return : Return decompressed string.

What is the difference between ZIP and gzip?

The most important difference is that gzip is only capable to compress a single file while zip compresses multiple files one by one and archives them into one single file afterwards. Thus, gzip comes along with tar most of the time (there are other possibilities, though). This comes along with some (dis)advantages.


1 Answers

Looks like this might have gotten a lot easier in Python3. This code seems to work so far:

data = bytes(json.dumps(packet), 'utf-8')
s_out = gzip.compress(data)
like image 114
Gregg Avatar answered Nov 08 '22 09:11

Gregg