175

问题很简单:我在 gDrive 上有一些数据,例如在 /projects/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)都建议仅主要将所有必要的数据加载到笔记本中。

但是,如果我有很多数据,它可能会非常复杂。有没有机会解决这个问题?

感谢帮助!

4

15 回答 15

379

编辑:截至 2020 年 2 月,现在有一个用于自动安装 Drive 的一流 UI。

首先,打开左侧的文件浏览器。它将显示一个“安装驱动器”按钮。单击后,您将看到安装 Drive 的权限提示,然后当您返回笔记本时,您的 Drive 文件将在没有设置的情况下显示。完成的流程如下所示:

驱动器自动挂载示例

原始答案如下。(这也适用于共享笔记本。)

您可以通过运行以下代码段来挂载您的 Google Drive 文件:

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

然后,您可以在文件浏览器侧面板中或使用命令行实用程序与您的云端硬盘文件进行交互。

这是一个示例笔记本

于 2018-09-12T17:36:16.453 回答
73

好消息,PyDrive在 CoLab 上有一流的支持!PyDrive 是 Google 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())

请注意,参数 to是与Google Drive HTTP APIdrive.ListFile使用的参数一致的字典(您可以自定义参数以适应您的用例)。q

知道在所有情况下,文件/文件夹都由 Google Drive 上的 id 编码(窥视1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk)。这要求您在 Google 云端硬盘中搜索与您要在其中进行搜索的文件夹相对应的特定 ID。

例如,导航到"/projects/my_project/my_data"位于您的 Google Drive 中的文件夹。

谷歌云端硬盘

看到它包含一些文件,我们要在其中下载到 CoLab。要获取文件夹的 id 以便 PyDrive 使用它,请查看 url 并提取 id 参数。在这种情况下,与文件夹对应的 url 是:

https://drive.google.com/drive/folders/1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk

其中 id 是 url 的最后一段:1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk

于 2018-01-22T16:17:26.933 回答
47

感谢您的精彩回答!从 Google 驱动器获取一些一次性文件到 Colab 的最快方法:加载驱动器助手并挂载

from google.colab import drive

这将提示授权。

drive.mount('/content/drive')

在新选项卡中打开链接->您将获得一个代码-将其复制回您现在可以访问谷歌驱动器检查的提示:

!ls "/content/drive/My Drive"

然后根据需要复制文件:

!cp "/content/drive/My Drive/xy.py" "xy.py"

确认文件已复制:

!ls
于 2018-11-01T01:28:42.720 回答
33

我所做的是首先:

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

然后

%cd /content/drive/My Drive/Colab Notebooks/

例如,在我可以读取 csv 文件之后

df = pd.read_csv("data_example.csv")

如果文件的位置不同,只需在“我的云端硬盘”后添加正确的路径

于 2020-08-19T09:46:48.450 回答
19

以前的大多数答案都有点(非常)复杂,

from google.colab import drive
drive.mount("/content/drive", force_remount=True)

我发现这是将谷歌驱动器安装到CO Lab的最简单和最快的方法,您mount directory location只需更改参数即可将 更改为您想要的任何内容drive.mount。它会给你一个链接来接受你的帐户的权限,然后你必须复制粘贴生成的密钥,然后驱动器将安装在选定的路径中。

force_remount仅在必须安装驱动器时使用,无论之前是否加载驱动器。如果您不想强制安装,可以忽略此 when 参数

编辑:查看此内容以找到更多IO在 colab https://colab.research.google.com/notebooks/io.ipynb中执行操作的方法

于 2019-05-08T06:19:48.930 回答
14

您不能将文件永久存储在 colab 上。虽然您可以从驱动器导入文件,但每次完成文件后,您都可以将其保存回来。

将 google 驱动器挂载到您的 Colab 会话

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

您可以像写入本地文件系统一样简单地写入 google 驱动器 现在,如果您看到您的 google 驱动器将加载到“文件”选项卡中。现在您可以从您的 colab 访问任何文件,您可以对其进行写入和读取。这些更改将在您的驱动器上实时完成,任何拥有您文件访问链接的人都可以从您的 colab 查看您所做的更改。

例子

with open('/content/gdrive/My Drive/filename.txt', 'w') as f:
   f.write('values')
于 2018-12-03T10:38:35.997 回答
5

我很懒,记性不好,所以我决定创建 更容易记忆和输入的easycolab :

import easycolab as ec
ec.mount()

确保首先安装它:!pip install easycolab

mount()方法基本上实现了这一点:

from google.colab import drive
drive.mount(‘/content/drive’)
cd ‘/content/gdrive/My Drive/’
于 2019-01-30T18:27:49.660 回答
5

要读取文件夹中的所有文件:

import glob
from google.colab import drive
drive.mount('/gdrive', force_remount=True)

#!ls "/gdrive/My Drive/folder"

files = glob.glob(f"/gdrive/My Drive/folder/*.txt")
for file in files:  
  do_something(file)
于 2020-07-21T18:53:20.833 回答
2
from google.colab import drive
drive.mount('/content/drive')

这对我来说非常完美,我后来能够使用该os库来访问我的文件,就像我在 PC 上访问它们一样

于 2020-08-01T03:52:28.933 回答
1

您可以简单地使用屏幕左侧的代码片段。 在此处输入图像描述

插入“在你的虚拟机中安装 Google Drive”

运行代码并将代码复制并粘贴到 URL 中

然后使用 !ls 检查目录

!ls /gdrive

在大多数情况下,您会在“/gdrive/My drive”目录中找到所需的内容

那么你可以像这样执行它:

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

file_path = glob.glob("/gdrive/My Drive/***.txt")
for file in file_path:
    do_something(file)
于 2018-10-15T15:27:10.453 回答
1

我写了一个类,将所有数据下载到“。” colab 服务器中的位置

整个事情可以从这里提取https://github.com/brianmanderson/Copy-Shared-Google-to-Colab

!pip install PyDrive


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

class download_data_from_folder(object):
    def __init__(self,path):
        path_id = path[path.find('id=')+3:]
        self.file_list = self.get_files_in_location(path_id)
        self.unwrap_data(self.file_list)
    def get_files_in_location(self,folder_id):
        file_list = drive.ListFile({'q': "'{}' in parents and trashed=false".format(folder_id)}).GetList()
        return file_list
    def unwrap_data(self,file_list,directory='.'):
        for i, file in enumerate(file_list):
            print(str((i + 1) / len(file_list) * 100) + '% done copying')
            if file['mimeType'].find('folder') != -1:
                if not os.path.exists(os.path.join(directory, file['title'])):
                    os.makedirs(os.path.join(directory, file['title']))
                print('Copying folder ' + os.path.join(directory, file['title']))
                self.unwrap_data(self.get_files_in_location(file['id']), os.path.join(directory, file['title']))
            else:
                if not os.path.exists(os.path.join(directory, file['title'])):
                    downloaded = drive.CreateFile({'id': file['id']})
                    downloaded.GetContentFile(os.path.join(directory, file['title']))
        return None
data_path = 'shared_path_location'
download_data_from_folder(data_path)
于 2019-05-17T16:51:47.933 回答
1

例如,要从 Google colab 笔记本中提取 Google Drive zip:

import zipfile
from google.colab import drive

drive.mount('/content/drive/')

zip_ref = zipfile.ZipFile("/content/drive/My Drive/ML/DataSet.zip", 'r')
zip_ref.extractall("/tmp")
zip_ref.close()
于 2020-02-04T09:35:09.867 回答
0

@wenkesj

我说的是复制目录及其所有子目录。

对我来说,我找到了一个解决方案,如下所示:

def copy_directory(source_id, local_target):
  try:
    os.makedirs(local_target)
  except: 
    pass
  file_list = drive.ListFile(
    {'q': "'{source_id}' in parents".format(source_id=source_id)}).GetList()
  for f in file_list:
    key in ['title', 'id', 'mimeType']]))
    if f["title"].startswith("."):
      continue
    fname = os.path.join(local_target, f['title'])
    if f['mimeType'] == 'application/vnd.google-apps.folder':
      copy_directory(f['id'], fname)
    else:
      f_ = drive.CreateFile({'id': f['id']})
      f_.GetContentFile(fname)

不过,我看起来 gDrive 不喜欢复制太多文件。

于 2018-01-25T07:20:19.020 回答
0

有很多方法可以读取 colab notebook(**.ipnb) 中的文件,其中一些是:

  1. 在运行时的虚拟机中挂载您的 Google Drive。这里&这里
  2. 使用 google.colab.files.upload()。最简单的解决方案
  3. 使用本机 REST API
  4. 使用 API 的包装器,例如PyDrive

方法1和2 对我有用,其余我无法弄清楚。如果有人可以,就像其他人在上面的帖子中尝试的那样,请写一个优雅的答案。提前致谢。!

第一种方法:

我无法安装我的谷歌驱动器,所以我安装了这些库

# Install a Drive FUSE wrapper.
# https://github.com/astrada/google-drive-ocamlfuse

!apt-get install -y -qq software-properties-common python-software-properties module-init-tools
!add-apt-repository -y ppa:alessandro-strada/ppa 2>&1 > /dev/null
!apt-get update -qq 2>&1 > /dev/null
!apt-get -y install -qq google-drive-ocamlfuse fuse

from google.colab import auth
auth.authenticate_user()
from oauth2client.client import GoogleCredentials
creds = GoogleCredentials.get_application_default()
import getpass

!google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret} < /dev/null 2>&1 | grep URL
vcode = getpass.getpass()
!echo {vcode} | google-drive-ocamlfuse -headless -id={creds.client_id} -secret={creds.client_secret}

安装和授权过程完成后,您首先安装驱动器。

!mkdir -p drive
!google-drive-ocamlfuse drive

安装后我可以挂载谷歌驱动器,你的谷歌驱动器中的所有内容都从/content/drive

!ls /content/drive/ML/../../../../path_to_your_folder/

现在,您可以path_to_your_folder使用上述路径简单地将文件夹中的文件读入 pandas。

import pandas as pd
df = pd.read_json('drive/ML/../../../../path_to_your_folder/file.json')
df.head(5)

你假设你使用你收到的绝对路径而不是使用 /../..

第二种方法

如果您要读取的文件存在于当前工作目录中,这很方便。

如果您需要从本地文件系统上传任何文件,您可以使用下面的代码,否则就避免它。!

from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('User uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))

假设您在 google 驱动器中的文件夹层次结构之下:

/content/drive/ML/../../../../path_to_your_folder/

然后,您只需将以下代码加载到 pandas 中。

import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df
于 2018-12-09T21:28:38.957 回答
0

考虑只下载带有永久链接的文件并gdown这里一样预安装

于 2020-08-29T14:45:35.250 回答