How do I gzip compress a string in Python?
问题 How do I gzip compress a string in Python? gzip.GzipFile exists, but that\'s for file objects - what about with plain strings? 回答1: If you want to produce a complete gzip-compatible binary string, with the header etc, you could use gzip.GzipFile together with StringIO: import StringIO import gzip out = StringIO.StringIO() with gzip.GzipFile(fileobj=out, mode="w") as f: f.write("This is mike number one, isn't this a lot of fun?") out.getvalue() # returns '\x1f\x8b\x08\x00\xbd\xbe\xe8N\x02\xff