I'm a little new to python, stuck in on the 6.00x (spring 2013) course. I'd hoped to try some of my new found knowledge but appear to have overreached.
The idea was to import a load a CSV file containing my bank statement into python. I'd then hoped place turn each transaction into an instance of a class. I'd then hoped to start playing around with the data to see what I could do but I appear to be failing at even the first hurdle, getting things nicely fitted into my Object Oriented program.
I started with this to import my file:
import csv
datafile = open('PATH/TO/file.csv', 'r')
datareader = csv.reader(datafile)
data = []
for row in datareader:
data.append(row)
That seems to work. I get a list of all the statement data that looks something like this below (You'll understand me not uploading the real data...)
[['date', 'type', 'details', 'amount', 'balance', 'accountname', 'accountdetails', 'blank_string'],['date', 'type', 'details', 'amount', 'balance', 'accountname', 'accountdetails', 'blank_string'],['date', 'type', 'details', 'amount', 'balance', 'accountname', 'accountdetails', 'blank_string'],['date', 'type', 'details', 'amount', 'balance', 'accountname', 'accountdetails', 'blank_string']]
so typing data[0] would get me:
['date', 'type', 'details', 'amount', 'balance', 'accountname', 'accountdetails', 'blank_string']
So then I created my class and constructor. With the idea of decomposing each one of these transactions into an easily accessible item.
class Transaction(object):
"""
Abstract class for building different kinds of transaction
"""
def __init__(self, data):
self.date = data[0]
self.trans_type = data[1]
self.description = data[2]
self.amount = data[3]
self.balance = data[4]
self.account_type = data[5]
self.account_details = data[6]
I find this works if I now enter
T1 = Transaction(data[0])
However I don't want to have to constantly type T1 =... T2=... t3=... t4=... there's LOADS of transctions it'd take forever!
So I tried this!
for i in range(len(data)):
eval("T" + str(i)) = Transaction(data[i])
But python really doesn't like that... It reports back:
SyntaxError: There is an error in your program: * can't assign to function call (FILENAME.py, line 80)
So my question is. Why can't I iteratively use the eval() function to assign my data as an instance into class Transaction(object)?
If there's no way around that, how might else I go about doing so?
I also have a lingering doubt that my mistake his suggests I've missed some point about Object Orientated Programming and when its appropriate to use it. Would I be better just feeding my csv data into a dictionary as its imported and playing around with it from there?
Many thanks! Huw