问题很简单:我在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)都建议只将所有必要的数据加载到笔记本中。

但是,如果我有很多数据,就会很复杂。 有没有解决这个问题的机会?

谢谢你的帮助!


当前回答

我所做的是:

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

Then

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

之后我就可以读取csv文件了

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

如果文件的位置不同,只需在“我的驱动器”后添加正确的路径

其他回答

好消息,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笔记本从谷歌驱动器读取图像

import glob
images_list = glob.glob("add google drive path/*.jpg")
print(images_list)

创建YOLOv4培训所需的training.txt文件

file = open("/content/drive/MyDrive/project data/obj/train.txt", "w") 
file.write("\n".join(images_list)) 
file.close() 

有很多方法来读取你的colab笔记本(**.ipnb)中的文件,其中一些是:

在运行时的虚拟机中安装谷歌驱动器。这里&,这里 使用google.colab.files.upload()。最简单的解决方案 使用本地REST API; 使用诸如PyDrive之类的API包装器

方法一和方法二对我有用,其他的我就不知道了。如果有人可以,就像其他人在上面的帖子中尝试的那样,请写一个优雅的答案。提前谢谢你!

第一种方法:

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

# 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/驱动器开始

!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])))

假设你在谷歌驱动器中有以下文件夹层次结构:

/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

我很懒,我的记忆力很差,所以我决定创建一个更容易记忆和输入的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/’
from google.colab import drive
drive.mount('/content/drive')

这对我来说是完美的 我后来能够使用操作系统库来访问我的文件,就像我在我的PC上访问它们一样