【问题标题】:KeyError when running codes to read file from google drive in Python运行代码以在 Python 中从谷歌驱动器读取文件时出现 KeyError
【发布时间】:2020-10-23 06:48:16
【问题描述】:

我想使用 Python 的 Visual Studio Code 上的 Google Drive API 直接从 Google Drive 读取文件。

这是部分代码:

file2 = drive.CreateFile({'id': file1['<the file ID of my file that is inside the Google Drive>']})
file2.GetContentString('testing.csv')

运行后,我得到一个

KeyError: KeyError('&lt;the file ID of my file that is inside the Google Drive&gt;')

我在互联网上搜索了解决此问题的可能方法,但到目前为止似乎没有任何效果......

我遵循了这个教程:Hands-on tutorial for managing Google Drive files with Python

【问题讨论】:

  • file2 = drive.CreateFile({'id': file1['id']}) file2.GetContentFile('testing.csv')
  • @ChatterOne 我仍然遇到同样的错误...
  • @user14489561 你的声明说你想从谷歌驱动器读取文件。您的代码显示您正在尝试在 google drive 中错误地创建文件。你到底想做什么?
  • @DalmTo 在读取 csv 文件的数据(存储在 google 驱动器中)并在我的 Visual Studio 代码的输出终端中显示 csv 文件的数据

标签: python python-3.x google-api google-drive-api google-api-python-client


【解决方案1】:

{'id': file1['id']} 表示您要检索 file1id - 一个您应该在前面的步骤中上传的文件

如果您没有在代码中定义 file1,您可以硬编码驱动器上任何文件的有效 id 作为参数。

示例:

file2 = drive.CreateFile({'id': '<the file ID of a csv file on your Google Drive>'})
file2.GetContentString('testing.csv')

【讨论】:

    【解决方案2】:

    上传文件到谷歌驱动器

    您需要发送MediaFileUpload 以使文件成为uploaded

    file_metadata = {'name': 'photo.jpg'}
    media = MediaFileUpload('files/photo.jpg', mimetype='image/jpeg')
    file = drive_service.files().create(body=file_metadata,
                                        media_body=media,
                                        fields='id').execute()
    print 'File ID: %s' % file.get('id')
    

    在 google drive web 应用程序上查看上传的文件。

    使用文件file.get 你会得到一个File resporce 响应。如果您上传的文件属于 Google 驱动器可以打开和显示的类型,它将有一个名为的属性。

    webViewLink 字符串 用于在相关 Google 编辑器或浏览器查看器中打开文件的链接。

    您可以使用该链接在 Google Drive Web 应用程序中打开文件。但是请注意,打开文件的用户必须拥有该文件的权限才能查看它。

    以编程方式读取数据。

    请记住,Google drive api 只是一个文件存储 api,它无法打开它只是存储它们的文件。如果您使用 CSV,那么您应该考虑将其转换为 Google 表格,然后使用 Google 表格 api 以编程方式访问数据

    【讨论】:

    • @DalmTo csv 文件已经上传到谷歌驱动器中...我只需要读取该 csv 文件的数据并将其显示在我的谷歌驱动器中
    • 执行 file.get 然后检查 webviewlink。这仅适用于 Google 驱动器可以打开的文件类型。
    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 2020-05-21
    • 2022-01-24
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    相关资源
    最近更新 更多