Python将csv转换为pickle会导致“write”属性

2024-10-01 11:40:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在处理一个小样本python文件。我有一个csv文件需要转换成pickle。这是我目前掌握的密码。在

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文件

^{pr2}$

当我阅读文件并将其放入一个列表中时,我无法对列表进行pickle处理。我还试图用a_list[0]而不是列表来对其进行pickle,结果显示错误泡菜。倾倒(primaryDetails,a_列表[0]) TypeError:文件必须具有“write”属性。我需要将数据放入一个列表中,并对其进行pickle以便将其保存到dbas mentioned here。有人能帮我找出我做错了什么吗。在


Tags: 文件csvnameselfagedeflocationgender
2条回答

您混淆了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)

Write a pickled representation of obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj).

[...]

The file argument must have a write() method that accepts a single bytes argument. It can thus be an on-disk file opened for binary writing, an io.BytesIO instance, or any other custom object that meets this interface.

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

在泡菜。倾倒()需要filestream对象和要写入文件的对象

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

相关问题 更多 >