【发布时间】:2016-01-14 23:02:43
【问题描述】:
我需要在内存中生成类似于数据的 csv 文件,然后将其编码为 base64,以便我可以保存它。所以基本上我不想为此在硬盘上创建文件。现在我通过创建 csv 文件然后对其数据进行编码、保存然后只是简单地删除 csv 文件(因为不再需要它)来解决这个问题。但是有没有办法跳过文件创建,但以同样的方式保存数据?我的意思是数据将用于使用 base64 再次打开 csv 文件。
import base64
import csv
from StringIO import StringIO
import os
def test_binary(self):
mylist = [['a', 'b'], ['c', 'd']]
with open("test.csv", "wb") as f:
writer = csv.writer(f)
writer.writerows(mylist)
myfile = open('test.csv', 'r')
stream = StringIO(myfile.read())
encoded = base64.b64encode(stream.getvalue())
self.test = encoded
myfile.close()
os.remove('test.csv')
【问题讨论】:
-
删除
'test.csv'并使用StringIO
标签: python csv memory base64 stringio