Python xlrd引擎传递的静态值错误
我正在尝试从url读取xls文件: 使用请求:Python xlrd引擎传递的静态值错误,python,excel,python-3.x,pandas,xlrd,Python,Excel,Python 3.x,Pandas,Xlrd,我正在尝试从url读取xls文件: 使用请求: page = requests.get(url) # xls url df = pd.read_excel(page.content,engine = 'xlrd') #engine is passed File "f:\python36\lib\site-packages\pandas\util\_decorators.py", line 118, in wrapper return func(*args, **kwargs)
page = requests.get(url) # xls url
df = pd.read_excel(page.content,engine = 'xlrd') #engine is passed
File "f:\python36\lib\site-packages\pandas\util\_decorators.py", line 118, in wrapper
return func(*args, **kwargs)
File "f:\python36\lib\site-packages\pandas\io\excel.py", line 230, in read_excel
io = ExcelFile(io, engine=engine)
File "f:\python36\lib\site-packages\pandas\io\excel.py", line 296, in __init__
raise ValueError('Must explicitly set engine if not passing in'
ValueError: Must explicitly set engine if not passing in buffer or path for io.
# if i put in random engine name it throws an unsupported engine error but with xlrd it throws must set engine
我尝试保存文件,然后读取它:
with open('file.xls','wb') as f:
f.write(page.content)
df = pd.read_excel('file.xls',engine='xlrd') #this works
编辑:
我已尝试传递它引发的page.text:
ValueError: embedded null character
如果
pd.read\u excel
的第一个参数是str
,它将被解释为文件(或URL)的路径。如果我们希望将文件内容直接传递给
read\u excel
,然后我们需要将内容包装在BytesIO
中,使其成为
类文件对象:
因此,使用
BytesIO = pd.io.common.BytesIO
df = pd.read_excel(BytesIO(page.content), engine='xlrd')
我的错误。我忘了
read\u excel
会将裸str
解释为文件路径。要传递内容,请将内容包装在一个StringIO
中,使其成为一个类似文件的对象。StringIO不起作用,但BytesIO起了作用,我不明白,page.content是byte,为什么用BytesIO包装会起作用?我曾认为(尽管可能是错误的)Python3中的pd.read.*
函数需要StringIO
s,但是在Python2中,同样的函数应该是BytesIO
s。也许我错了,而且是pd。read_excel总是期望BytesIO
s。下面的一个例子似乎表明,在使用pd时,将字节内容包装在BytesIO
中是一种方法。read_excel
:啊,提示数据应该以字节的形式保存:“#如果io是一个url,希望以字节的形式保存数据…”