Reputation: 119
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.
Upvotes: 9
Views: 67678
Reputation: 111
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')
Upvotes: 11
Reputation:
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])
Upvotes: 3