如何使用 pandas.read_excel() 直接从 Dropbox 的 API 读取 Excel 文件?

HaP*_*ran 2 python dropbox-api pandas

我有兴趣比较存储在 Dropbox 中的两个版本的小型 Excel 文件作为单独的版本。

使用 Python SDK,特别是files_download() 方法,我得到一个 requests.models.Response 对象,但我无法让pandas.read_excel()使用它。

这是代码片段:

with open(resp.content, "rb") as handle:
    df = pandas.read_excel(handle.read())
Run Code Online (Sandbox Code Playgroud)

错误:

TypeError('file() argument 1 must be encoded string without null bytes, not str',)
Run Code Online (Sandbox Code Playgroud)

我知道我缺少一些基本的东西,可能需要将文件编码为二进制文件。(尝试过 base64.b64encode 和其他一些东西,但还没有成功。)我希望有人可以帮助我指出正确的方向,可能是 io 模块?

我正在使用 Python 2.7.15

为免生疑问,我特别希望避免首先将 Excel 文件保存到文件系统的步骤。我确信我能实现更广泛的目标这种方式,但优化我试图从Dropbox的文件直接读入大熊猫DataFrames,那read_excel()方法接受一个文件-事实上类似物体的手段,我——我应该能够做到这一点。

基本上,我认为总结了我目前正在经历的痛苦。我需要将 Dropbox 的响应转换为类文件对象的形式。

Ivo*_*ers 5

以下代码将执行您想要的操作。

# Imports and initialization of variables
from contextlib import closing # this will correctly close the request
import io
import dropbox
token = "YOURTOKEN" #get token on https://www.dropbox.com/developers/apps/
dbx = dropbox.Dropbox(token)
yourpath = "somefile.xlsx" # This approach is not limited to excel files

# Relevant streamer
def stream_dropbox_file(path):
    _,res=dbx.files_download(path)
    with closing(res) as result:
        byte_data=result.content
        return io.BytesIO(byte_data)

# Usage
file_stream=stream_dropbox_file(yourpath)
pd.read_excel(file_stream)
Run Code Online (Sandbox Code Playgroud)

这种方法的好处在于,使用 io.BytesIO 将数据转换为一般的类文件对象。因此,你也可以用它来阅读的东西像CSV的使用pd.read_csv()

代码也应该适用于非 Pandas io 方法,例如加载图像,但我没有明确测试过。