首页 > 解决方案 > 从谷歌驱动器获取 CSV,然后加载到熊猫

问题描述

我的目标是从谷歌驱动器中读取 .csv 文件并将其加载到数据框中。

我在这里尝试了一些答案,但问题是,该文件不是公开的,需要身份验证。

我查看了护目镜驱动 API,但我被困在那里,我不知道如何前进。我确实设法打开了 google sheet 并将其加载到数据框中,但这是不同的,这是一个适用于 google sheet 的示例。

service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()
sheets_file = sheet.values().get(
                     spreadsheetId=sheet_id,
                     range=sheet_range
                     ).execute()
    
header = sheets_file.get('values', [])[0]   # Assumes first line is header!
values = sheets_file.get('values', [])[1:]  # Everything else is data.
  
if not values:
    print('No data found.')
else:
    all_data = []
    for col_id, col_name in enumerate(header):
        column_data = []
        for row in values:
            column_data.append(row[col_id])
        ds = pd.Series(data=column_data, name=col_name)
        all_data.append(ds)
        df = pd.concat(all_data, axis=1)
        print(df.head())

我也看到了一些 google colab 方法,但我不能使用它,因为我仅限于使用 python,关于如何解决这个问题的任何想法?

标签: pythonpandasgoogle-drive-api

解决方案


我相信你的目标和情况如下。

  • 您想从 Google Drive 上的 CSV 文件下载 CSV 数据。
  • 您可以使用 googleapis for python 从 Google 电子表格中获取值。

模式一:

在此模式中,CSV 数据是使用 googleapis 下载的。下载的 CSV 数据保存为文件。并通过Drive API v3中的“Files:get”方法检索该值。

示例脚本:

file_id = "###"  # Please set the file ID of the CSV file.

service = build('drive', 'v3', credentials=creds)
request = service.files().get_media(fileId=file_id)
fh = io.FileIO("sample.csv", mode='wb')
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
    status, done = downloader.next_chunk()
    print("Download %d%%." % int(status.progress() * 100))
  • 在这种情况下,可以将 CSV 数据转换为带有df = pd.read_csv("sample.csv").

模式二:

在此模式中,作为一种简单的方法,访问令牌使用 from creds。下载的 CSV 数据不会保存为文件。并通过Drive API v3中的“Files:get”方法检索该值。

示例脚本:

file_id = "###"  # Please set the file ID of the CSV file.

access_token = creds.token
url = "https://www.googleapis.com/drive/v3/files/" + file_id + "?alt=media"
res = requests.get(url, headers={"Authorization": "Bearer " + access_token})
print(res.text)
  • 在这种情况下,可以将 CSV 数据直接转换为带有df = pd.read_csv(io.StringIO(res.text)).

笔记:

  • 在以下脚本中,请包括https://www.googleapis.com/auth/drive.readonly和/或的范围https://www.googleapis.com/auth/drive。当您修改范围时,请重新授权范围。这样,修改后的范围就包含在访问令牌中。请注意这一点。

参考:


推荐阅读