【问题标题】:How to display a data parsed from csv file through a link using Python如何使用 Python 通过链接显示从 csv 文件解析的数据
【发布时间】:2014-03-02 13:35:08
【问题描述】:

我从一个链接中读取了一个 csv 文件:

当我在文本编辑器上打开 csv 文件格式时,它看起来像这样。

name, id, age, city
,steve, 1, 34, NY
,Rob, 2, 29, NY
,Ashly, 3, 28, NY

#!/usr/bin/python

url = 'http://domainname.com/file.csv'
response = urllib2.urlopen(url).read()
output   = StringIO.StringIO(response)

cr       = csv.reader((line.replace('NUL','') for line in output), delimiter=",")

当我使用迭代 cr 时

for row in cr:
    print row

我得到的输出与实际文件数据不同。

['\x1b']
['^']
['\xd3']
['\xd4']
['\xe7']
['\x88']
['\xf7']

【问题讨论】:

    标签: python parsing url csv encode


    【解决方案1】:

    我已经使用下面提到的链接中的 csv 文件尝试了您的代码,并且一切正常。所有行都正确打印,这意味着从 url 正确接收到 csv 文件。

    import urllib2
    import StringIO
    import csv
    
    
    url = "http://www.andrewpatton.com/countrylist.csv"
    response = urllib2.urlopen(url).read()
    output   = StringIO.StringIO(response)
    
    cr       = csv.reader((line.replace('NUL','') for line in output), delimiter=",")
    
    for row in cr:
            print row
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-04
      • 2015-05-08
      • 2020-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      相关资源
      最近更新 更多