I am trying to parse CSV using python and would like to be able to index elements in a string so that they can be retrieved using row[0] , row[1] , etc.
So far this is my code:
def get_bitstats(): url = 'http://bitcoincharts.com/t/trades.csv?symbol=mtgoxUSD' data = urllib.urlopen(url).read() dictReader = csv.DictReader(data) obj = BitData() for row in dictReader: obj.datetime = datetime.datetime.fromtimestamp(int(row['0'])/1000000) q = db.Query(BitData).filter('datetime', obj.datetime) if q != None: raise ValueError(obj.datetime + 'is already in database') else: obj.price = row['1'] obj.amount = row['2'] obj.put()
This returns KeyError: '0' , and I have no idea how to configure it. I entered this into an interactive shell and at startup
for row in dictReader: print row
I get this as output:
{'1': '3'} {'1': '6'} {'1': '2'} {'1': '6'} {'1': '9'} {'1': '8'} {'1': '6'} {'1': '4'} {'1': '4'} {'1': '', None: ['']} {'1': '4'} {'1': '2'} {'1': '.'} {'1': '0'} {'1': '5'} {'1': '7'} {'1': '1'} {'1': '6'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '', None: ['']} {'1': '0'} {'1': '.'} {'1': '0'} {'1': '1'} {'1': '0'} {'1': '0'} {'1': '5'} {'1': '4'} {'1': '2'} {'1': '5'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '0'} {'1': '1'} {'1': '3'} {'1': '6'} {'1': '2'} {'1': '6'} {'1': '9'} {'1': '8'} {'1': '6'} {'1': '4'} {'1': '4'}
and many and many lines. (since I'm sure CSV is thousands of digits)
Why is my CSV print so it is to split the string into a list of 3 ints , such as [130534543, 47.00009, 23001.9000]
EDIT:
since in the answer, I used the wrong csv function in my code above, but although the fix gave me a list, the list itself was in the same format as the dict, so:
['1'] ['2'] ['1'] ['3'] ['8'] ['3'] ['5'] . . .
Turns out I also had to remove .read() from data = urllib.urlopen(url).read() .
source share