【问题标题】:Pandas xlrd engine passed still value errorPandas xlrd 引擎通过了仍然值错误
【发布时间】:2023-03-25 05:10:02
【问题描述】:

我正在尝试从 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)
  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

【问题讨论】:

    标签: python excel python-3.x pandas xlrd


    【解决方案1】:

    如果pd.read_excel 的第一个参数是str,它被解释为文件(或URL)的路径。如果我们希望将文件的内容直接传递给 read_excel,那么我们需要将内容包装在BytesIO中,使其成为 类文件对象:

    因此,使用

    BytesIO = pd.io.common.BytesIO
    df = pd.read_excel(BytesIO(page.content), engine='xlrd')
    

    【讨论】:

    • 我的错误。我忘记了read_excel 会将裸露的str 解释为文件路径。要传递内容,请将内容包装在 StringIO 中,使其成为类似文件的对象。
    • StringIO 不起作用,但是 BytesIO 起作用了,我不明白,page.content 是 byte,为什么包装在 BytesIO 中起作用?
    • 我曾认为(虽然可能是错误的)在 Python3 中 pd.read_* 函数需要 StringIOs,但在 Python2 中相同的函数需要 BytesIOs。也许我错了,pd.read_excel 总是期待BytesIOs。
    • 这是一个例子,它似乎表明在BytesIO 中包装字节内容是使用pd.read_excel 时要走的路:stackoverflow.com/a/48326707/190597
    • 啊,the source code提示数据应该保存为bytes:“#如果io是url,想把数据保存为字节...”
    猜你喜欢
    • 1970-01-01
    • 2019-08-27
    • 2014-07-05
    • 2018-11-18
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 2014-09-29
    相关资源
    最近更新 更多