Python - generate csv file in memory and then encode its data into base64?
You could pass StringIO()
to the csv writer directly:
>>> import base64
>>> import csv
>>> from io import StringIO
>>> mylist = [['a', 'b'], ['c', 'd']]
>>> f = StringIO()
>>> csv.writer(f).writerows(mylist)
>>> base64.b64encode(f.getvalue().encode())
b'YSxiDQpjLGQNCg=='
Python 2
>>> import base64
>>> import csv
>>> from StringIO import StringIO
>>> mylist = [['a', 'b'], ['c', 'd']]
>>> f = StringIO()
>>> csv.writer(f).writerows(mylist)
>>> base64.b64encode(f.getvalue())
'YSxiDQpjLGQNCg=='