简体   繁体   中英

Converting .pkl file to .csv file

I am working on a python file that requires large data but I am not able to edit my data. Can someone suggest me a code on how can I convert a .pkl file to .csv file.

I have found a similar question here:

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

You need this example from there:

import base64, csv
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])

I modify it to read from your pickle file:

import pickle        
import base64
import csv

your_pickle_obj = pickle.loads(open('data.pkl', 'rb').read())
with open('output.csv', 'a', encoding='utf8') as csv_file:
    wr = csv.writer(csv_file, delimiter='|')
    pickle_bytes = pickle.dumps(your_pickle_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])

Simplest and easy way to convert PKL file to csv

import pickle as pkl
import pandas as pd
with open("file.pkl", "rb") as f:
    object = pkl.load(f)
    
df = pd.DataFrame(object)
df.to_csv(r'file.csv')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM