将.pkl文件转换为.csv文件

时间:2019-05-07 08:42:34

标签: python export-to-csv pickle

我正在处理需要大量数据的python文件,但无法编辑数据。有人可以向我建议如何将.pkl文件转换为.csv文件的代码。

2 个答案:

答案 0 :(得分:1)

将 PKL 文件转换为 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')

答案 1 :(得分:0)

我在这里找到了类似的问题:

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

您需要从此处获取此示例:

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])

我将其修改为从您的泡菜文件中读取:

import pickle        
import base64

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])