2017-06-29 16 views
0

私は小さなサンプルのPythonファイルを扱っています。私はピックルに変換する必要があるCSVファイルがあります。これはこれまでのコードです。私は、ファイルを読んで、私はリストをpickle化することはできませんよ、リストに入れてPython - csvをpickleに変換すると 'write'属性のエラーが発生する

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]) TypeError:ファイルは '書き込み'属性を持っている必要があります。私はリストにデータを入れ、それをpickbleしてdb as mentioned hereに保存する必要があります。誰かが私が間違っていることを理解するのを助けることができますか?

答えて

2

ファイルに書き込みたい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は()あなたは漬物用pickle.dump()

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

ドキュメントに引数の順番を混同している

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

私は例外TypeError 'と言っても同じエラーを取得しています:ファイルが '書き込み' attribute'を持っている必要があります。 –

+2

引数の順序は 'pickle.dump(obj、file)'である必要があります https://docs.python.org/3.6/library/pickle.html#pickle.dump –

+0

ThanksHåkenLid。あなたが正しい... –

関連する問題