【问题标题】:Python - converting csv to a pickle causes 'write' attribute errorPython - 将 csv 转换为 pickle 会导致“写入”属性错误
【发布时间】:2017-06-29 11:43:51
【问题描述】:

我正在处理一个小的示例 python 文件。我有一个需要转换为泡菜的 csv 文件。这是我到目前为止的代码。

import csv
import pickle


class primaryDetails:
    def __init__(self, name, age, gender, contactDetails):
        self.name = name
        self.age = age
        self.gender = gender
        self.contactDetails = contactDetails

    def __str__(self):
        return "{} {} {} {}".format(self.name, self.age, self.gender, self.contactDetails)

    def __iter__(self):
        return iter([self.name, self.age, self.gender, self.contactDetails])

class contactDetails:
    def __init__(self, cellNum, phNum, Location):
        self.cellNum = cellNum 
        self.phNum = phNum
        self.Location = Location

    def __str__(self):
        return "{} {} {}".format(self.cellNum, self.phNum, self.Location)

    def __iter__(self):
        return iter([self.cellNum, self.phNum, self.Location])


a_list = []

with open("t_file.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        a = contactDetails(row[3], row[4], row[5])
        a_list.append(primaryDetails(row[0], row[1], row[2] , a))

file = open('writepkl.pkl', 'wb')
# pickle.dump(a_list[0], primaryDetails)
pickle.dump(primaryDetails, a_list[0])
file.close()

csv 文件

Bat,45,M,123456789,98764,Gotham
Sup,46,M,290345720,098484,Krypton
Wwomen,30,F,758478574,029383,Themyscira
Flash,27,M,3646348348,839484,Central City
Hulk,50,M,52903852398,298392,Ohio

当我读取文件并将其放入列表时,我无法挑选列表。我还尝试使用a_list[0] 而不是列表来腌制它,它给了我错误 pickle.dump(primaryDetails, a_list[0]) 类型错误:文件必须具有“写入”属性。我需要将数据放在一个列表中并腌制,以便我可以将其保存到 db as mentioned here。有人可以帮我弄清楚我做错了什么。

【问题讨论】:

    标签: python csv pickle


    【解决方案1】:

    你混淆了pickle.dump()的参数顺序

    with open('writepkl.pkl', 'wb') as output_file:
        pickle.dump(a_list, output_file)
    

    pickle 和所有其他标准库模块的文档可以在https://docs.python.org 找到。

    pickle.dump(obj, file, protocol=None, *, fix_imports=True)

    将 obj 的腌制表示写入打开的文件对象文件。 这相当于 Pickler(file, protocol).dump(obj)。

    [...]

    file 参数必须有一个 write() 方法,该方法接受单个 字节参数。因此,它可以是为二进制文件打开的磁盘文件 写入、io.BytesIO 实例或任何其他满足 这个界面。

    https://docs.python.org/3.6/library/pickle.html#pickle.dump

    【讨论】:

      【解决方案2】:

      Pickle.dump() 需要一个文件流对象和要写入文件的对象

      file = open("file.pkl",'wb')
      pickle.dump(a_list[0], file)
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2011-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多