如何将python对象pickle到csv文件中?

时间:2018-01-26 06:58:00

标签: python csv pickle python-3.6

我正在尝试将python对象pickle到csv文件中。我想把对象的pickle写成我文件中的第三列。我想使用pickle来避免为我的复杂对象编写序列化。

写入csv的代码:

 with open(self.file_path, 'a') as csv_file:
        wr = csv.writer(csv_file, delimiter='|')
        row = ['klines', symbol]
        row.extend(pickle.dumps(object))
        wr.writerow(row)

读取csv的代码:

 with open(self.simulation_file_name, 'r') as csv_file:
        line = csv_file.readline()
        while line != '':
            line = line.strip('\n')
            columns = line.split('|')
            event_type = line.pop(0)
            symbol = line.pop(0)
            pickled = line.pop(0)
            klines = pickle.loads(klines)

我收到以下错误:

TypeError: a bytes-like object is required, not 'str'

1 个答案:

答案 0 :(得分:2)

要在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

P.S。如果您没有编写utf8文件(例如ascii文件),只需替换编码方法。

P.S。用CSV写入字节可能很难实现。另一种方法是使用转储对象转储整个dict作为值并将密钥存储在CSV中。