【问题标题】:read excel file to a dataframe without downloading the file locally无需在本地下载文件即可将 excel 文件读取到数据框
【发布时间】:2022-12-11 22:04:37
【问题描述】:

我试图在不在本地下载文件的情况下读取谷歌驱动器上的 excel 文件


credentialFileOfServiceAccount =  'x.json'
scope = ['https://www.googleapis.com/auth/drive'] #edited by ashraf
creds = ServiceAccountCredentials.from_json_keyfile_name(credentialFileOfServiceAccount, scope)
print(creds)



 spreadsheetId=file.get("id")
                gauth = GoogleAuth()
                gauth.LocalWebserverAuth()
                url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
                res = requests.get(url, headers={"Authorization": "Bearer " + gauth.attr[creds].access_token})

# 2. The downloaded XLSX data is read with `pd.read_excel`.
sheet = "Sheet1"
values = pd.read_excel(BytesIO(res.content), usecols=None, sheet_name=sheet)
print(values)

那是我收到的错误

InvalidConfigError:无效的客户端机密文件('打开文件时出错','client_secrets.json','没有这样的文件或目录',2)

【问题讨论】:

  • 仅供参考:您正在将文件下载到内存中,只是没有将其保存到计算机上的文件中。你的标题有点偏。对于该代码如何导致该错误,我有点困惑。错误状态为 client_secrets.json,但您的代码显示为 x.json。也就是说,您的代码找不到文件 client_secrets.json 确保 credentialFileOfServiceAccount 实际上指向文件所在的目录。
  • 你能验证这是一个 xlsx 文件而不是一个已经转换为谷歌表格的文件吗?

标签: python pandas google-drive-api


【解决方案1】:

您的问题很可能与您没有为服务帐户凭据文件正确设置路径有关。

我得到这个工作。

#   To install the Google client library for Python, run the following command:
#   pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib

from __future__ import print_function

import pandas as pd
import openpyxl
import io
from googleapiclient.http import MediaIoBaseDownload
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/drive']

# Service account key file
KEYFILE = "C:YouTubedevServiceAccountCred.json";

# file id
FILEID = "1JTbcnbcmuN0olIUJ-FYIHLnSUDePfbw7";

def main():

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        KEYFILE,
        scopes=SCOPES,
    )

    try:
        service = build('drive', 'v3', credentials=credentials)

        # Call the Drive v3 API
        # assign a variable with the found id name
        request = service.files().get_media(fileId=FILEID)
        file = io.BytesIO()
        downloader = MediaIoBaseDownload(file, request)
        done = False
        while done is False:
            status, done = downloader.next_chunk()
            print(F'Download {int(status.progress() * 100)}.')
            sheet = "Sheet1"
            df = pd.read_excel(file,  engine='openpyxl')
            print(df.head())



    except HttpError as error:
        # TODO(developer) - Handle errors from drive API.
        print(f'An error occurred: {error}')


if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 2021-09-29
    • 2012-11-19
    • 2019-10-16
    • 2017-08-26
    • 1970-01-01
    • 2016-03-23
    相关资源
    最近更新 更多