我试图从给定的URL读取一个csv文件,使用Python 3.x:
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)
我有以下错误
"期望的文件路径名称或类文件对象,已获得<类'bytes'>类型"
我该如何解决这个问题?我使用的是Python 3.4
你遇到的问题是,输入变量's'的输出不是csv文件,而是html文件。
为了得到原始的csv,你必须修改url为:
“https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv”
第二个问题是read_csv需要一个文件名,我们可以通过使用StringIO from io模块来解决这个问题。
第三个问题是request.get(url)。内容传递一个字节流,我们可以使用request.get(url)来解决这个问题。文本。
最终结果是这样的代码:
from io import StringIO
import pandas as pd
import requests
url='https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv'
s=requests.get(url).text
c=pd.read_csv(StringIO(s))
输出:
>>> c.head()
Country Region
0 Algeria AFRICA
1 Angola AFRICA
2 Benin AFRICA
3 Botswana AFRICA
4 Burkina AFRICA
正如我评论的那样,你需要使用一个StringIO对象和解码,即c=pd.read_csv(io.StringIO(s.decode("utf-8")))如果使用请求,你需要解码为.content返回字节如果你使用.text,你只需要传递s,因为s = requests.get(url)。text c = pd.read_csv(StringIO(s))。
一个更简单的方法是直接将原始数据的正确url传递给read_csv,你不需要传递object这样的文件,你可以传递一个url,所以你根本不需要请求:
c = pd.read_csv("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv")
print(c)
输出:
Country Region
0 Algeria AFRICA
1 Angola AFRICA
2 Benin AFRICA
3 Botswana AFRICA
4 Burkina AFRICA
5 Burundi AFRICA
6 Cameroon AFRICA
..................................
从文档中可以看出:
filepath_or_buffer:
字符串或文件句柄/ StringIO
字符串可以是URL。有效的URL方案包括http、ftp、s3和file。对于文件url,需要一个主机。例如,本地文件可以是file://localhost/path/to/table.csv