Python has a zipfile
module which allows you to read/write zip archives.
The zipfile.ZipFile
class has a writestr()
method that can create a "file" in the archive directly from a string.
So no, you don't have to write your string to a file before archiving it.
Update after question edit
You say you don't want an archive but the linked PHP code does just that -- creates a PK-Zip archive. In Python you do the same with zipfile
. Here's an example that creates a zip and adds one file to it -- all in-memory, without physical files.
import zipfile
from cStringIO import StringIO
f = StringIO()
z = zipfile.ZipFile(f, 'w', zipfile.ZIP_DEFLATED)
z.writestr('name', 'some_bytes_to_compress')
z.close()
output_string = f.getvalue()
output_string
will be the compressed content in PK-Zip format.
If you control both sending and receiving side and you don't need to send multiple compressed files in one chunk of data, using PK-Zip is overkill. Instead, you could just use the zlib
module which implements the compression for PK-Zip.
import zlib
output_string = zlib.compress('some_bytes_to_compress')
And then you can decompress it (assuming Python):
decompressed_string = zlib.decompress(output_string)