如何使用Colaboratory(Google)从Google Drive读取数据

3

我是新手,想在Colaboratory上建立一个小项目并将其存储在我的谷歌云端硬盘上。在我的谷歌云端硬盘上,我创建了一个名为'TheProject'的文件夹,在其中创建了两个文件夹:'code'和'data'。在'code'文件夹中,我创建了一个新的Colab笔记本,并在'data'文件夹中拥有多个数据集。

问题

如何从谷歌云端硬盘上的文件夹中读取数据到Colab笔记本中?例如:

data = pd.read_excel('SOME_PATH/TheProject/data/my_data.xlsx')

其中SOME_PATH应指示如何到达主文件夹'TheProject'并从'data'文件夹中读取数据。

1个回答

8

在Google Drive上右键单击您的文件并获取其共享链接,从该链接中提取文件ID。

! pip install pydrive
# these classes allow you to request the Google drive API
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)
file_id = '<your_file_id>'
downloaded = drive.CreateFile({'id': file_id})
# allows you to temporarily load your file in the notebook VM

# assume the file is called file.csv and it's located at the root of your drive
downloaded.GetContentFile('file.csv')

一旦您执行这些命令,系统会提示您进入一个链接,要求您授权给Google Drive。它会提供一个令牌,您必须在文本框中输入该令牌。
现在您准备好加载您的文件了:
data = pd.read_csv('file.csv')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接