I read a csv file from a link :

csv file format looks like this when I open it on text editor.

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=",")

when I iterate over the cr using

for row in cr:
    print row

I get this output which is diferent than the actual file data.

['\x1b']
['^']
['\xd3']
['\xd4']
['\xe7']
['\x88']
['\xf7']
有帮助吗?

解决方案

I have tried your code with a csv file from link mentioned below and everything is working perfectly fine. All the rows are printing correctly that means csv file is correctly received from url.

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top