如何将python对象腌制到csv文件中? [英] How can I pickle a python object into a csv file?

查看:107
本文介绍了如何将python对象腌制到csv文件中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将python对象腌制到csv文件中.我想将一个对象的泡菜作为文件中的第三列.我想使用pickle避免为我的复杂对象编写序列化.

I am trying to pickle a python object into a csv file. I want to write the pickle of an object as the third column in my file. I want to use pickle to avoid writing serialization for my complex objects.

要写入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'

推荐答案

要在CSV之类的文本文件中写入字节/二进制,请使用base64或其他方法来避免任何转义问题.代码简化和假定为python3.

To write bytes/binary in text file like CSV, use base64 or other methods to avoid any escaping problem. Code simplified & python3 assumed.

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. If you are not writing a utf8 file (e.g. ascii file), simply replace the encoding method.

P.S.用CSV写入字节是可能的,但几乎没有问题.一种替代方法是使用转储的对象作为值转储整个dict并将密钥存储在CSV中.

P.S. Writing bytes in CSV is possible yet hardly elegant. One alternative is dumping a whole dict with dumped objects as values and storing keys in the CSV.

这篇关于如何将python对象腌制到csv文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆