![](/img/trans.png)
[英]How do you read excel sheets using index instead of name with pandas.read_excel?
[英]How do I read an Excel file directly from Dropbox's API using pandas.read_excel()?
我對比較存儲在Dropbox中作為單獨版本的兩個較小的Excel文件版本感興趣。
使用Python SDK,特別是files_download()方法 ,我得到了一個request.models.Response對象,但是我很難讓pandas.read_excel()使用它。
這是代碼片段:
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()方法采用類似於文件的對象這一事實意味着-我認為我應該能夠做到這一點。
基本上,我認為這總結了我目前正在經歷的痛苦。 我需要將Dropbox的響應轉換為類似文件的對象的形式。
以下代碼將執行您想要的操作。
# 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之類的 pd.read_csv()
。
該代碼也應適用於非熊貓io方法,例如加載圖像,但我尚未對此進行明確測試。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.