我试图从给定的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
更新:从熊猫0.19.2你现在可以直接传递read_csv() url,虽然这将失败,如果它需要认证。
对于较旧的pandas版本,或者如果您需要身份验证,或者出于任何其他http容错原因:
使用熊猫。使用类文件对象作为第一个参数的Read_csv。
如果你想从字符串中读取csv,你可以使用io.StringIO。
对于URL https://github.com/cs109/2014_data/blob/master/countries.csv,你得到html响应,而不是原始的csv;你应该使用github页面中Raw链接给出的url来获得原始csv响应,即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')))
注:
在Python 2中。x时,字符串缓冲区对象是StringIO。StringIO
正如我评论的那样,你需要使用一个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
你遇到的问题是,输入变量'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