Programming/Python

Python으로 특정한 파일을 Google Drive 자동 업로드하기

makeitworth 2024. 6. 28. 18:24

준비 사항

  1. Python 3.x
  2. pip (Python 패키지 관리자)
  3. Google 계정
  4. Google Cloud Console 프로젝트

1단계: 필요한 라이브러리 설치

pip install google-auth-oauthlib google-auth-httplib2 google-api-python-client pandas

2단계: Google Cloud Console 설정

  1. Google Cloud Console에 접속
  2. 새 프로젝트를 생성하거나 기존 프로젝트를 선택
  3. API 및 서비스 대시보드로 이동하여 "Google Drive API"를 활성화

 

4. 사용자 인증 정보를 만들고 OAuth 2.0 클라이언트 ID를 다운로드

5. 다운로드한 JSON 파일의 이름을 credentials.json으로 변경하고 작업 디렉토리에 저장

3단계: Python 스크립트

아래의 파이썬 코드를 저장하고 그대로 실행하면 된다. 
folder_id 만 변경하면 되는데, 아무것도 입력하지 않으면, 내드라이브에 바로 저장이 되고, 폴더 ID는 내가 업로드하고자 하는 폴더의 url 주소의 가장 마지막 부분이 folder id에 해당한다. 아래 이미지의 하이라이트된 부분

 

import pandas as pd
from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
import os

# Google Drive API 스코프 설정
SCOPES = ['https://www.googleapis.com/auth/drive.file']

def get_drive_service():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return build('drive', 'v3', credentials=creds)


def upload_to_drive(filename, folder_id=None):
    service = get_drive_service()
    file_metadata = {
        'name': filename,
        'parents': [folder_id]  # 특정 폴더에 업로드하기 위한 설정
    }
    if folder_id:
        file_metadata['parents'] = [folder_id]
    media = MediaFileUpload(filename, resumable=True)
    file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    print(f"파일이 업로드되었습니다. 파일 ID: {file.get('id')}")

if __name__ == '__main__':
    # create_csv()
    folder_id = [내가 저장하고자 하는 드라이브 내 폴더의 폴더 아이디]
    upload_to_drive('webposter_ver_sampled_data_50.csv', folder_id)