问题很简单:我在gDrive上有一些数据,例如在
/项目/ my_project / my_data *。
我也有一个简单的笔记本在gColab。
所以,我想做的是:
for file in glob.glob("/projects/my_project/my_data*"):
do_something(file)
不幸的是,所有的例子(例如https://colab.research.google.com/notebook#fileId=/v2/external/notebooks/io.ipynb)都建议只将所有必要的数据加载到笔记本中。
但是,如果我有很多数据,就会很复杂。
有没有解决这个问题的机会?
谢谢你的帮助!
好消息,PyDrive对CoLab有一流的支持!PyDrive是谷歌Drive python客户端的包装器。下面是一个关于如何从一个文件夹下载所有文件的例子,类似于使用glob + *:
!pip install -U -q PyDrive
import os
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)
# choose a local (colab) directory to store the data.
local_download_path = os.path.expanduser('~/data')
try:
os.makedirs(local_download_path)
except: pass
# 2. Auto-iterate using the query syntax
# https://developers.google.com/drive/v2/web/search-parameters
file_list = drive.ListFile(
{'q': "'1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk' in parents"}).GetList()
for f in file_list:
# 3. Create & download by id.
print('title: %s, id: %s' % (f['title'], f['id']))
fname = os.path.join(local_download_path, f['title'])
print('downloading to {}'.format(fname))
f_ = drive.CreateFile({'id': f['id']})
f_.GetContentFile(fname)
with open(fname, 'r') as f:
print(f.read())
注意驱动的参数。ListFile是一个字典,它与谷歌Drive HTTP API使用的参数相一致(您可以自定义q参数,以调优您的用例)。
要知道,在所有情况下,文件/文件夹都是通过谷歌驱动器上的id进行编码的(参见1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk)。这要求您在谷歌驱动器中搜索与您想要在其中查找的文件夹对应的特定id。
例如,导航到“/projects/my_project/my_data”文件夹
位于您的谷歌驱动器。
它包含一些文件,我们希望将这些文件下载到CoLab。要获得文件夹的id以便PyDrive使用它,请查看url并提取id参数。在本例中,文件夹对应的url为:
其中id是url的最后一部分:1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk。
不能在colab上永久存储文件。虽然你可以从你的驱动器导入文件,每次当你完成了文件,你可以把它保存回来。
将谷歌驱动器挂载到Colab会话
from google.colab import drive
drive.mount('/content/gdrive')
您可以像写入本地文件系统一样简单地写入谷歌驱动器
现在如果你看到你的谷歌驱动器将加载在文件选项卡。现在您可以从您的colab访问任何文件,您可以写入以及读取它。这些更改将在您的驱动器上实时完成,任何拥有您文件访问链接的人都可以从您的colab查看您所做的更改。
例子
with open('/content/gdrive/My Drive/filename.txt', 'w') as f:
f.write('values')
之前的大多数答案都有点(非常)复杂,
from google.colab import drive
drive.mount("/content/drive", force_remount=True)
我发现这是最简单和最快的方法来安装谷歌驱动器到CO实验室,你可以改变挂载目录的位置,只要改变drive.mount的参数。它会给你一个链接,接受与您的帐户的权限,然后你必须复制粘贴生成的密钥,然后驱动器将被安装在选定的路径。
Force_remount仅在必须挂载驱动器时使用,而不管之前是否加载了驱动器。如果不想强制挂载,可以忽略这个when参数
编辑:查看这篇文章,了解更多在colab https://colab.research.google.com/notebooks/io.ipynb中执行IO操作的方法