NeuroWhAI의 잡블로그

[Python] PyDrive로 구글 드라이브에 있는 파일 읽기 본문

개발 및 공부/라이브러리&프레임워크

[Python] PyDrive로 구글 드라이브에 있는 파일 읽기

NeuroWhAI 2018. 4. 1. 11:03


Colab에서 외부 파일을 불러오고 싶을때 이 방식을 쓰면 가능합니다.

# Install the PyDrive wrapper & import libraries.
# This only needs to be done once per notebook.
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
 
# Authenticate and create the PyDrive client.
# This only needs to be done once per notebook.
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
 
# Download a file based on its file ID.
#
# A file ID looks like: laggVyWshwcyP6kEI-y_W3P8D26sz
file_id = 'REPLACE_WITH_YOUR_FILE_ID'
downloaded = drive.CreateFile({'id': file_id})
print('Downloaded content "{}"'.format(downloaded.GetContentString()))

위 코드를 사용하면 됩니다.

!pip install ...는 파이썬 코드가 아니라 저 명령어로 PyDrive를 설치하란 소립니다.

(Colab에선 그냥 그대로 복붙해서 쓰셔도 됩니다.)

file_id는 파일의 공유 링크에서 찾을 수 있습니다.


또 파일의 내용 뿐만 아니라 다른 정보(이름, mime타입, 크기, 공유 링크 등)를 얻고 싶다면 아래와 같이 할 수 있습니다.

downloaded['title'] # 파일 이름
downloaded['mimeType'] # MIME 타입

더 자세한 정보는 레퍼런스를 참고하세요.




Comments