Google Colab: Google 드라이브에서 데이터를 읽는 방법
문제는 간단합니다.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/v2/vari/disc/io.ipynb)에서는 주로 필요한 모든 데이터만 노트북에 로드하도록 권장하고 있습니다.
하지만 데이터가 많으면 상당히 복잡할 수 있습니다.이 문제를 해결할 기회가 있습니까?
도와줘서 고마워요!
편집: 2020년 2월부터 드라이브를 자동으로 마운트할 수 있는 1등급 UI가 추가되었습니다.
먼저 왼쪽에 있는 파일브라우저를 엽니다.Mount Drive(드라이브 마운트) 버튼이 표시됩니다.클릭하면 드라이브를 마운트하기 위한 사용 권한 프롬프트가 표시되고 노트북으로 돌아가면 드라이브 파일이 설정되지 않은 상태로 표시됩니다.완성된 흐름은 다음과 같습니다.
원래의 대답은 다음과 같습니다.(공유 노트북에서도 계속 사용할 수 있습니다.)
다음 코드 스니펫을 실행하여 Google 드라이브 파일을 마운트할 수 있습니다.
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 드라이브에서 ID(1SuKSw8M4ACBznKjnNrYvJ5wxuqJ-YCk 피프)로 인코딩됩니다.이렇게 하려면 검색을 루트할 폴더에 해당하는 특정 ID를 Google Drive에서 검색해야 합니다.
를 들어, 를를 to to to to to to the the the the to to로 합니다."/projects/my_project/my_data"
구글을 이용하다
CoLab에 다운로드할 파일이 포함되어 있는지 확인합니다.PyDrive에서 사용하기 위해 폴더 ID를 가져오려면 url을 보고 id 파라미터를 추출합니다.이 경우 폴더에 대응하는 URL은 다음과 같습니다.
여기서 id는 URL의 마지막 부분입니다.1SuKSw8M4ACBznKjnNrYvJ5wxuqJ-YCK
좋은 답변 감사합니다!Google 드라이브에서 Colab으로 일회성 파일 몇 개를 가져오는 가장 빠른 방법: 드라이브 도우미 로드 및 마운트
from google.colab import drive
이것에 의해, 인가를 요구하는 프롬프트가 표시됩니다.
drive.mount('/content/drive')
새 탭에서 링크를 엽니다.-> 코드가 나타납니다. Google 드라이브에 액세스할 수 있게 되었는지 확인하는 프롬프트에 다시 복사합니다.
!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)
구글 드라이브를 CO Lab에 마운트하는 가장 쉽고 빠른 방법이라는 것을 알게 되었습니다.mount directory location
할 수 있도록 하기 위해 매개 만 하면 됩니다.drive.mount
계정 사용 권한을 승인하기 위한 링크가 나타납니다. 그런 다음 생성된 키를 복사 붙여넣어야 선택한 경로에 드라이브가 마운트됩니다.
force_remount
이전에 로드되었는지 여부에 관계없이 드라이브를 마운트해야 하는 경우에만 사용됩니다.로 마운트하지가 있는 경우 이를 할 수 .
를 하는 다른 해 주세요.IO
colab https://colab.research.google.com/notebooks/io.ipynb에서의 조작
파일을 collab에 영구적으로 저장할 수 없습니다.드라이브에서 파일을 가져올 수도 있고 파일을 다 쓸 때마다 파일을 다시 저장할 수도 있습니다.
Colab 세션에 Google 드라이브를 마운트하려면
from google.colab import drive
drive.mount('/content/gdrive')
로컬 파일 시스템에 쓰듯이 구글 드라이브에 쓰기만 하면 됩니다. 지금 보면 구글 드라이브가 파일 탭에 로드됩니다.이제 콜라브에서 모든 파일에 액세스할 수 있으며, 이 파일에서 읽고 쓸 수 있습니다.변경은 드라이브에서 실시간으로 수행되며, 파일에 대한 액세스 링크가 있는 사용자는 콜라브에서 사용자가 변경한 내용을 볼 수 있습니다.
예
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 드라이브 마운트" 삽입
코드를 실행하고 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 노트북(**.ipnb)의 파일을 읽는 방법에는 여러 가지가 있습니다.그 중 몇 가지는 다음과 같습니다.
- 런타임의 가상 머신에 Google 드라이브를 마운트하는 중입니다.여기와 여기
- google.colab 사용.files.files.files가 가장 쉬운 솔루션
- 네이티브 REST API 사용
- PyDrive와 같은 API에 대한 래퍼 사용
방법 1과 방법 2는 나에게 효과가 있었고, 나머지는 알아낼 수 없었다.만약 할 수 있는 사람이 있다면, 다른 사람이 시도했던 것처럼 우아한 답변을 써주세요.잘 부탁드립니다!
첫 번째 방법:
Google 드라이브를 마운트할 수 없어서 이 라이브러리를 설치했습니다.
# 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
설치 후 Google 드라이브를 마운트할 수 있었습니다. Google 드라이브의 모든 것이 /content/drive에서 시작됩니다.
!ls /content/drive/ML/../../../../path_to_your_folder/
이제 파일을 읽기만 하면 됩니다.path_to_your_folder
위 경로를 사용하여 팬더로 접습니다.
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/
그리고 팬더에게 로딩하려면 아래 코드만 입력하면 됩니다.
import pandas as pd
import io
df = pd.read_json(io.StringIO(uploaded['file.json'].decode('utf-8')))
df
모든 데이터를 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 노트북에서 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는 파일을 너무 많이 복사하는 것을 좋아하지 않는 것 같습니다.
와 「Permanent Link」를 사용하여 하는 것을 .gdown
다음과 같이 프리 인스톨 완료
collab 노트북을 사용하여 Google 드라이브에서 이미지 읽기
import glob
images_list = glob.glob("add google drive path/*.jpg")
print(images_list)
트레이닝을 작성하다.txt 파일, YOLOv4 트레이닝에 필요
file = open("/content/drive/MyDrive/project data/obj/train.txt", "w")
file.write("\n".join(images_list))
file.close()
언급URL : https://stackoverflow.com/questions/48376580/google-colab-how-to-read-data-from-my-google-drive
'programing' 카테고리의 다른 글
PHP에서 유용한 오류 메시지를 얻으려면 어떻게 해야 합니까? (0) | 2022.10.13 |
---|---|
file_get_contents(): 코드 1에서 SSL 작업이 실패했습니다.암호화를 활성화하지 못했습니다. (0) | 2022.10.13 |
MySQL에서 선택한 값의 쉼표로 구분된 문자열 (0) | 2022.10.13 |
열려 있는 MySQL 연결 수를 확인하려면 어떻게 해야 합니까? (0) | 2022.10.13 |
GitHub에서 Python 패키지를 설치하는 방법은? (0) | 2022.10.13 |