要在CSV之类的文本文件中写入字节/二进制,请使用base64或其他方法来避免任何转义问题。代码简化&python3假定。import base64
with open('a.csv', 'a', encoding='utf8') as csv_file:
wr = csv.writer(csv_file, delimiter='|')
pickle_bytes = pickle.dumps(obj) # unsafe to write
b64_bytes = base64.b64encode(pickle_bytes) # safe to write but still bytes
b64_str = b64_bytes.decode('utf8') # safe and in utf8
wr.writerow(['col1', 'col2', b64_str])
# the file contains
# col1|col2|gANdcQAu
with open('a.csv', 'r') as csv_file:
for line in csv_file:
line = line.strip('\n')
b64_str = line.split('|')[2] # take the pickled obj
obj = pickle.loads(base64.b64decode(b64_str)) # retrieve
另外,如果你没有写utf8文件(例如ascii文件),只需替换编码方法。
p.S.在CSV中写入字节是可能的,但很难做到优雅。另一种方法是转储一个完整的dict,其中转储的对象作为值并将密钥存储在CSV中。