Python 3 In Memory Zipfile Error. string argument expected, got 'bytes'
ZipFile
writes its data as bytes, not strings. This means you'll have to use BytesIO
instead of StringIO
on Python 3.
The distinction between bytes and strings is new in Python 3. The six compatibility library has a BytesIO
class for Python 2 if you want your program to be compatible with both.
The problem is that io.StringIO()
is being used as the memory buffer, when it needs to be io.BytesIO
. The error is occurring because the zipfile code is eventually calling the StringIO().Write() with bytes when StringIO expects a string.
Once it's changed to BytesIO()
, it works:
from io import BytesIO
from pprint import pprint
import zipfile
in_memory_data = BytesIO()
in_memory_zip = zipfile.ZipFile(
in_memory_data, "w", zipfile.ZIP_DEFLATED, False)
in_memory_zip.debug = 3
filename_in_zip = 'test_filename.txt'
file_contents = 'asdf'
in_memory_zip.writestr(filename_in_zip, file_contents)