How can I pickle a python object into a csv file?

后端 未结 1 1063
无人及你
无人及你 2021-01-16 07:42

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 serializ

相关标签:
1条回答
  • 2021-01-16 08:37

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

    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.

    0 讨论(0)
提交回复
热议问题