簡體   English   中英

Google Colab:如何從我的谷歌驅動器中讀取數據?

[英]Google Colab: how to read data from my google drive?

問題很簡單:我在 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 )建議僅主要將所有必要數據加載到筆記本中。

但是,如果我有很多數據,它可能會非常復雜。 有沒有機會解決這個問題?

感謝幫助!

編輯:截至 2020 年 2 月,現在有一個用於自動安裝 Drive 的一流 UI。

首先,打開左側的文件瀏覽器。 它將顯示一個“安裝驅動器”按鈕。 單擊后,您將看到安裝 Drive 的權限提示,之后您的 Drive 文件將在您返回筆記本時無需設置即可顯示。 完成的流程如下所示:

驅動器自動掛載示例

原始答案如下。 (這也適用於共享筆記本。)

您可以通過運行以下代碼片段來掛載 Google Drive 文件:

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

然后,您可以在文件瀏覽器側面板中或使用命令行實用程序與您的雲端硬盤文件進行交互。

這是一個示例筆記本

好消息, 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())

請注意, drive.ListFile的參數是一個字典,與Google Drive HTTP API使用的參數一致(您可以自定義q參數以適應您的用例)。

要知道,在所有情況下,文件/文件夾都是由 Google Drive 上的 id(查看 1SooKSw8M4ACbznKjnNrYvJ5wxuqJ-YCk )編碼的。 這要求您在 Google 雲端硬盤中搜索與您要在其中進行搜索的文件夾對應的特定 ID。

例如,導航到位於 Google 雲端硬盤中的文件夾"/projects/my_project/my_data"

谷歌雲端硬盤

看到它包含一些我們要下載到 CoLab 的文件。 要獲取文件夾的 id 以便 PyDrive 使用它,請查看 url 並提取 id 參數。 在這種情況下,文件夾對應的 url 是:

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

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

謝謝你的好答案! 從 Google Drive 將一些一次性文件獲取到 Colab 的最快方法:加載 Drive 助手並掛載

from google.colab import drive

這將提示授權。

drive.mount('/content/drive')

在新選項卡中打開鏈接 -> 您將獲得一個代碼 - 將其復制回提示中,您現在可以訪問谷歌驅動器檢查:

!ls "/content/drive/My Drive"

然后根據需要復制文件:

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

確認文件已復制:

!ls

我所做的首先是:

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

然后

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

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

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

如果您有不同的文件位置,只需在“我的驅動器”后添加正確的路徑

以前的大多數答案都有點(非常)復雜,

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

我發現這是將 google drive 掛載到CO Lab的最簡單和最快的方法,您只需更改drive.mount的參數即可將mount directory location更改為您想要的任何mount directory location 它會給你一個鏈接來接受你的帳戶的權限,然后你必須復制粘貼生成的密鑰,然后驅動器將安裝在選定的路徑中。

force_remount僅在您必須掛載驅動器時使用,而不管其之前是否已加載。如果您不想強制掛載,則可以忽略此 when 參數

編輯:查看此內容以找到更多在 colab 中執行IO操作的方法https://colab.research.google.com/notebooks/io.ipynb

您不能在 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')

我很懶,記性不好,所以我決定創建更容易記憶和輸入的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/’

要讀取文件夾中的所有文件:

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)
from google.colab import drive
drive.mount('/content/drive')

這對我來說非常有用,我后來可以使用os庫來訪問我的文件,就像我在 PC 上訪問它們一樣

您可以簡單地使用屏幕左側的代碼片段。 在此處輸入圖片說明

插入“在 VM 中安裝 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)

我寫了一個類,將所有數據下載到 '.' 在 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)

例如,要從 Google colab notebook 中提取 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()

@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 不喜歡復制太多文件。

有很多方法可以讀取 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])))

假設您的谷歌驅動器中的文件夾層次結構低於:

/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

考慮只用下載永久鏈路和文件gdown預裝喜歡這里

使用 colab notebook 從 google drive 讀取圖像

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

創建 training.txt 文件,YOLOv4 訓練需要

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

27/12/2022 更新:

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

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM