2017-06-29 53 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

感謝哈肯蓋子。你是對的... –