2

I'm trying to open a csv file from a url but for some reason I get an error saying that there is an invalid mode or filename. I'm not sure what the issue is. Help?

url = "http://...."
data = open(url, "r")
read = csv.DictReader(data)

4 Answers 4

2

Download the stream, then process:

import urllib2
url = "http://httpbin.org/get"
response = urllib2.urlopen(url)
data = response.read()
read = csv.DictReader(data)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Esparta Palma for the answer. It helped me. Here's the version that worked for me: '''' import urllib2 url = "httpbin.org/get" response = urllib2.urlopen(url) data = response.read().decode('utf-8') read = csv.DictReader(data.splitlines()) for row in read: # Do something ''''
2

I recommend pandas for this:

import pandas as pd
read = pandas.io.parsers.read_csv("http://....", ...)

please see the documentation.

1 Comment

Alternatively, you can use the standard urllib to download from the URL and parse the stream.
2

You can do the following :

import csv
import urllib2

url = 'http://winterolympicsmedals.com/medals.csv'
response = urllib2.urlopen(url)
cr = csv.reader(response)

for row in cr:
 print row

Comments

-2

Slightly tongue in cheek:

require json
>>> for line in file(','):
...     print json.loads('['+line+']')

CSV is not a well defined format. JSON is so this will parse a certain type of CSV correctly every time.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.