【问题标题】:Csv file not found error in Google colaboratory notebooksGoogle 协作笔记本中未找到 CSV 文件错误
【发布时间】:2018-06-27 15:41:50
【问题描述】:

我正在尝试将存储在谷歌驱动器中的 csv 文件加载到 colab 笔记本。当我尝试加载文件时,它显示“找不到文件”。将存储在谷歌驱动器中的文件加载到 colab 笔记本的过程是什么?

【问题讨论】:

标签: google-colaboratory


【解决方案1】:

我发现最简单的方法是在 colab 中安装谷歌驱动器:

from google.colab import drive
drive.mount('/content/gdrive')

然后使用 '/content/gdrive/My Drive/' 作为文件路径的前缀。假设您在谷歌驱动器的数据目录中有一个文本文件。然后您可以使用以下代码访问它:

open('/content/gdrive/My Drive/data/filename.txt').read()

【讨论】:

  • 这应该被标记为解决方案。认证过程非常简单
【解决方案2】:

要从 Google Drive 访问文件,您需要使用 PyDrive 或 Drive Rest API 加载文件。

在访问文件之前运行下面的代码

!pip install -U -q PyDrive

from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials

# 1. Authenticate and create the PyDrive client.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

# 2. Load a file by ID and create local file.
downloaded = drive.CreateFile({'id':'fileid'}) # replace fileid with Id of file you want to access
downloaded.GetContentFile('export.csv') # now you can use export.csv 

【讨论】:

  • 什么是id?不能确定。
  • 如果你尝试在 google drive 中获取某个文件的可共享链接,会有一个 id 参数。
【解决方案3】:

试试:

from google.colab import drive
drive.mount('/content/drive')

此命令将带您进入 Google 身份验证步骤。您应该会看到一个屏幕,其中包含 Google Drive File Stream 想要访问您的 Google 帐户。在您允许后,复制给定的验证码并将其粘贴到 Colab 的框中。

在笔记本中,单击笔记本左上角的木炭>,然后单击文件。找到您之前创建的数据文件夹并找到您的数据。右键单击您的数据并选择复制路径。将此复制的路径存储到变量中,您就可以开始了。

file = "copied path"

df = pd.read_csv(file)
df.head()

提示:添加斜杠 (/) 作为目录名称的一部分(适用于 Linux 或 Mac 用户)。例如:“/content/drive/My Drive/Colab Notebooks/data/xpto.csv”

【讨论】:

    【解决方案4】:
    from google.colab import files
    
    files.upload()
    

    添加这些行,然后您可以手动上传文件,希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2020-07-17
      • 2023-03-26
      相关资源
      最近更新 更多