Kam Kam - 1 month ago 4
Python Question

Inserting file record into object and then into dictionary

class Customer:
def __init__(self,custid,name,addr,city,state,zipcode):
self.custid=custid
self.name=name
self.addr=addr
self.city=city
self.state=state
self.zipcode=zipcode
self.memberLevel=BasicMember()
self.monthlySpending =0

def changeLevel(self,level):
if level == 'gold':
self.memberLevel = GoldMember()
elif level == 'silver':
self.memberLevel = SilverMember()
else:
self.memberLevel = BasicMember()


Above is my customer class. I am trying to read customer data from a file and map it to a customer class object. Afterwards I want to insert each object in the dictionary. Currently I'm having trouble as it gives me an error:

cc=Customer.Customer(*item)
TypeError: __init__() takes 7 positional arguments but 61 were given.


Customer1
is the name of the module I am importing.

for line in open('customers.dat','r'):
item=line.rstrip()
cc=Customer1.Customer(*item)
s2=item.split(',',1)[0]
d[s2]=[cc]


Here is some sample data in my
Customer.dat
file:

310933237,Temmin Wexley,898 Sullustan Street,Geonosis,MA,02100
286659823,Mace Windu,741 Bantha Street,Jakku,MA,02330
234101312,Wuher,932 Besalisk Street,Coruscant,MA,02169
721728168,Yaddle,30 Amani Road,D'Qar,MA,01508
492621787,Yoda,860 Amani Road,Endor,NH,03801

Answer

When you call Customer(*item) you are passing in a string (e.g. "310933237,Temmin Wexley,898 Sullustan Street,Geonosis,MA,02100") and so it gets expanded to the argument list 3, 1, 0, 9, .... etc.

Change it to something like:

item=line.rstrip()
input = line.split(',')
cc = Customer(*input)

to get your arguments split out correctly.

Comments