简体   繁体   English

Python3:无法腌制DictReader实例

[英]Python3: Can't pickle DictReader instance

I have a file csvHelper.py where I read the csv and store it in a dictionary using DictReader. 我有一个文件csvHelper.py,我在其中读取csv,并使用DictReader将其存储在字典中。 But when I try to pickle this dictionary, I get the following error: 但是,当我尝试使这本词典腌制时,出现以下错误:

_pickle.PicklingError: Can't pickle : it's not the same object as _csv.reader _pickle.PicklingError:无法腌制:它与_csv.reader不同

For reference, the relevant part of the code: 供参考,代码的相关部分:

allData = DictReader(open('xyz.csv', 'rt'))

for row in allData:
    row["Element name"] = row["Element name"]+'##'

dataStore = open('myPickleFile', 'wb')
pickle.dump(allData, dataStore)

The code is not pickling the dictioary, but DictReader . 代码不是腌制字典,而是DictReader

If you want dump all dictionaries, gather them in a list, and dump the list: 如果要转储所有字典,请将它们收集在一个列表中,然后转储该列表:

import pickle
from csv import DictReader

with open('xyz.csv', 'rt') as f:
    allData = DictReader(f)

    rows = []
    for row in allData:
        row["Element name"] = row["Element name"]+'##'
        rows.append(row)

with open('myPickleFile', 'wb') as f:
    pickle.dump(rows, f)

DictReader is indeed unpicklable. DictReader确实是不可拾取的。 Try converting allData to a list prior to processing: 尝试在处理之前将allData转换为列表:

allData = list(DictReader(open('xyz.csv', 'rt')))

This would also ensure that the changes you do to the individuals rows while iterating aren't lost. 这也可以确保您在迭代过程中对各个行所做的更改不会丢失。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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