Question
I am using Python 3.4 with IPython and have the following code. I'm unable to read a csv-file from the given URL:
- import pandas as pd
- import requests
- url="https://github.com/cs109/2014_data/blob/master/countries.csv"
- s=requests.get(url).content
- c=pd.read_csv(s)
How can I fix this?
How-To
Just as the error suggests , pandas.read_csv needs a file-like object as the first argument. If you want to read the csv from a string, you can use io.StringIO (Python 3.x) or StringIO.StringIO (Python 2.x) . Also, for the URL - https://github.com/cs109/2014_data/blob/master/countries.csv - you are getting back html response , not raw csv, you should use the url given by the Raw link in the github page for getting raw csv response , which is - https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv
- import pandas as pd
- import io
- import requests
- url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
- s=requests.get(url).content
- c=pd.read_csv(io.StringIO(s.decode('utf-8')))
沒有留言:
張貼留言