python中csv库row_Python CSV阅读器将Row作为列表

Im trying to parse a CSV using python and would like to be able to index items in a row so they can be accessed using row[0], row[1] and so on.

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 set it up. I did input this into an interactive shell and when running

for row in dictReader:

print row

I get this as the 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 on and on for thousands and thousands of lines. ( as Im sure the CSV is thousands of digits)

Why is my CSV printing this way and is there anyway to separate a row into a list of 3 ints such as [130534543, 47.00009, 23001.9000]

EDIT:

as the Answer states I was using the wrong csv function in my code above but even though fixing it gave me a list the list itself was in the same format as the dict such that:

['1']

['2']

['1']

['3']

['8']

['3']

['5']

.

.

.

It turns out I also had to remove the .read() from data = urllib.urlopen(url).read().

解决方案

csv.reader will return each row as a list

reader = csv.reader(data)

for line_list in reader:

pass

# line_list is a list of the data contained in a row so you can access line_list[0]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值