Python CSV阅读器将Row作为列表 [英] Python CSV reader return Row as list

查看:660
本文介绍了Python CSV阅读器将Row作为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用python解析CSV,并希望能够在一行中索引项,以便可以使用 row [0] row [1] 等等。

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()

KeyError:'0',我不知道如何设置它。我没有将它输入到交互式shell中,当为dictReader中的行运行

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

我得到这个作为输出:

{'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'}

数千行。 (因为我确定CSV是数千位数)

and on and on for thousands and thousands of lines. ( as Im sure the CSV is thousands of digits)

为什么我的CSV打印这种方式,并有反正将一行分成3 ints ,例如[130534543,47.00009,23001.9000]

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]

编辑:

因为答案状态我在上面的代码使用错误的csv函数,但即使修复它给了我一个列表的列表本身是与dict相同的格式,如:

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']
.
.
.



原来我也不得不删除 .read code>从 data = urllib.urlopen(url).read()

推荐答案

csv.reader 将以列表形式返回每一行

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]

这篇关于Python CSV阅读器将Row作为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆