我正在尝试将存储在google驱动器中的csv文件加载到colab笔记本中。当我尝试加载文件时,它显示“找不到文件”。将存储在google驱动器中的文件加载到colab笔记本的过程是什么?
要从Google云端硬盘访问文件,您需要使用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
我找到的最简单的方法是在colab中安装google驱动器:
from google.colab import drive
drive.mount('/content/gdrive')
然后使用'/ content / gdrive / My Drive /'作为文件路径的前缀。假设您在google驱动器的数据目录中有一个文本文件。然后您可以使用以下代码访问它:
open('/content/gdrive/My Drive/data/filename.txt').read()
尝试:
from google.colab import drive
drive.mount('/content/drive')
此命令将带您进入Google身份验证步骤。您应该会看到一个包含Google云端硬盘文件流的屏幕,想要访问您的Google帐户。在您获得许可后,复制给定的验证码并将其粘贴到Colab的框中。
在笔记本中,单击笔记本左上角的“炭”>,然后单击“文件”。找到您之前创建的数据文件夹并查找数据。右键单击您的数据,然后选择“复制路径”。将此复制的路径存储到变量中,您就可以开始使用了。
file = "copied path"
df = pd.read_csv(path)
df.head()
提示:添加斜杠(/)作为目录名称的一部分(适用于Linux或Mac用户)。例如:“/ content / drive / My Drive / Colab Notebooks / data / xpto.csv”