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

时间:2018-12-09 22:07:14

标签: python pandas dropbox-api

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

使用Python SDK,特别是files_download() method,我得到了一个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()方法需要一个文件- like 对象的意思是-我认为-我应该能够做到这一点。

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

1 个答案:

答案 0 :(得分:0)

以下代码将满足您的要求。

func main(){
    const dir = "/etc/"
    filesInfo, e := ioutil.ReadDir(dir)
    var fileNames = make([]string, 0, 10)
    for i,v:=range filesInfo{
        if !v.IsDir() {
            fileNames = append(fileNames, v.Name())
        }
    }

    var fileNumber = len(fileNames)
    var contents = make([]string, fileNumber, 10)
    wg := sync.WaitGroup{}
    wg.Add(fileNumber)

    for i,_:=range content {
        go func(i int){
            defer wg.Done()
            buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
            defer file.Close()  
            content[i] = string(buf)
        }(i)   
    }
    wg.Wait()
}

此方法的优点在于,使用io.BytesIO可以将数据转换为类似于文件的常规对象。因此,您还可以使用它来读取带有# 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) csv 之类的内容。

该代码也应适用于非熊猫io方法,例如加载图像,但我尚未对此进行明确测试。

相关问题