I want to create a csv-file within a zipfile - without using temp files or so. But the zipfile-handler seems to need a byte-object. The csv-handler seems to output str-only.
What is the best / common way to handle this?
test.py:
import zipfile
import csv
with zipfile.ZipFile("test.zip",mode='w',compression=zipfile.ZIP_DEFLATED) as zip:
with zip.open('itemgroups.csv', mode='w') as csvfile:
csvoutput = csv.writer(csvfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csvoutput.writerow(['id', 'value'])
~$ python3 test.py
Traceback (most recent call last):
File "test.py", line 7, in <module>
csvoutput.writerow(['id', 'value'])
File "/usr/lib/python3.7/zipfile.py", line 1094, in write
self._crc = crc32(data, self._crc)
TypeError: a bytes-like object is required, not 'str'
I thought about it and created an adapter class:
class zipadapter:
def __init__(self, zipfile):
self.zipfile = zipfile
def write(self, string):
self.zipfile.write(string.encode())
I use it this way:
with zipfile.ZipFile("test.zip",mode='w',compression=zipfile.ZIP_DEFLATED) as zip:
with zip.open('itemgroups.csv', mode='w') as csvfile:
csvstrfile = zipadapter(csvfile)
csvoutput = csv.writer(csvstrfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
csvoutput.writerow(['id', 'value'])
And... it works. Elegant? I don't know. Best way? I doubt that - if you have better ideas, don't hesitate to answer ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With