【问题标题】:How do I read an Excel file directly from Dropbox's API using pandas.read_excel()?如何使用 pandas.read_excel() 直接从 Dropbox 的 API 读取 Excel 文件?
【发布时间】:2018-12-09 22:07:13
【问题描述】:

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

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

这里是sn-p的代码:

with open(resp.content, "rb") as handle:
    df = pandas.read_excel(handle.read())

错误:

TypeError('file() argument 1 must be encoded string without null bytes, not str',)

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

我使用的是 Python 2.7.15

为免生疑问,我特别希望避免首先将 Excel 文件保存到文件系统的步骤。我确定我可以通过这种方式实现更广泛的目标,但为了优化,我试图将 Dropbox 中的文件直接读取到 pandas DataFrames 中,并且 read_excel() 方法需要一个文件-like 对象意味着——我认为——我应该能够做到这一点。

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

【问题讨论】:

  • 看起来您在rb 之后缺少一个结束引号?
  • 请尝试通过下载到文件的方式将excel保存到本地。参考它的路径,包括。文件名和“C:....rb.xlsx”作为熊猫数据框的输入。恐怕熊猫收到了错误的输入类型。如果这对您没有帮助,请发表评论。
  • 谢谢,@Mike_H。这是一个很好的建议,但在回应您的评论时,我进一步澄清说我希望避免这种情况。
  • 我对 pandas 不熟悉,所以我不能帮助它,但请注意,您从 dropbox 获得的 resp.content files_download 方法是文件数据本身(不是文件句柄)。 (在提供的代码中,您似乎正在尝试在 resp.content 中的任何内容的本地路径中 open 一个本地文件,这可能不是您想要的。)
  • @HaPsantran 你找到解决这个问题的方法了吗?

标签: python pandas dropbox-api


【解决方案1】:

下面的代码会做你想做的。

# 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)

这种方法的优点是使用 io.BytesIO 将数据转换为通用的文件类对象。因此,您还可以使用它通过pd.read_csv() 读取诸如 csv's 之类的内容。

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

【讨论】:

  • 万岁@Ivo Merchiers;万岁啊
猜你喜欢
  • 1970-01-01
  • 2018-01-26
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 2023-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多