How to read a CSV file from a URL with Python? How to read a CSV file from a URL with Python? python python

How to read a CSV file from a URL with Python?


Using pandas it is very simple to read a csv file directly from a url

import pandas as pddata = pd.read_csv('https://example.com/passkey=wedsmdjsjmdd')

This will read your data in tabular format, which will be very easy to process


You need to replace open with urllib.urlopen or urllib2.urlopen.

e.g.

import csvimport urllib2url = 'http://winterolympicsmedals.com/medals.csv'response = urllib2.urlopen(url)cr = csv.reader(response)for row in cr:    print row

This would output the following

Year,City,Sport,Discipline,NOC,Event,Event gender,Medal1924,Chamonix,Skating,Figure skating,AUT,individual,M,Silver1924,Chamonix,Skating,Figure skating,AUT,individual,W,Gold...

The original question is tagged "python-2.x", but for a Python 3 implementation (which requires only minor changes) see below.


You could do it with the requests module as well:

url = 'http://winterolympicsmedals.com/medals.csv'r = requests.get(url)text = r.iter_lines()reader = csv.reader(text, delimiter=',')