2017-06-29 54 views
0

我在一个小样本的Python文件的工作。我有一个csv文件需要转换为泡菜。这是迄今为止的代码。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]) 类型错误:文件必须有一个“写”属性。我需要把数据列表和咸菜这让我可以将它保存到数据库as mentioned here。有人能帮我弄清楚我做错了什么。

回答

2

你的参数的顺序混合高达pickle.dump()

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

的咸菜文档FileStream对象和对象所有其他标准库模块可在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

1

和pickle.dump()需要要写入文件

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

我收到同样的错误说'类型错误:文件必须有一个“写” attribute'。 –

+2

参数的顺序应该是'和pickle.dump(OBJ,文件)' https://docs.python.org/3.6/library/pickle.html#pickle.dump –

+0

感谢哈肯盖子。你是对的... –