Pythonを使用してGoogle ドライブにファイルをアップロードする

2024年6月25日

Pythonを使用してGoogle ドライブにファイルをアップロードするには、Google Drive APIを使用する必要があります。以下は、PythonでGoogle Drive APIを使用してファイルをアップロードする基本的な手順です。

  1. Google Cloud Platformでプロジェクトを作成する:
  2. 必要なPythonパッケージをインストールする:
    bash
    pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
    
  3. 認証と認可を設定する:
    • Google Drive APIを使用するには、OAuth 2.0認証が必要です。認証情報を含むcredentials.jsonファイルを取得してプロジェクトディレクトリに保存します。
  4. Pythonコードを書く:
    • 以下は、ファイルをアップロードするPythonスクリプトの例です。
python
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
import os

# 認証情報ファイルのパス
credentials_path = 'credentials.json'

# スコープ
SCOPES = ['https://www.googleapis.com/auth/drive.file']

def authenticate():
    flow = InstalledAppFlow.from_client_secrets_file(credentials_path, SCOPES)
    credentials = flow.run_local_server(port=0)
    return credentials

def create_drive_service():
    credentials = authenticate()
    drive_service = build('drive', 'v3', credentials=credentials)
    return drive_service

def upload_file(file_path, mime_type='text/plain'):
    drive_service = create_drive_service()

    file_name = os.path.basename(file_path)
    file_metadata = {'name': file_name}

    media = MediaFileUpload(file_path, mimetype=mime_type)
    file = drive_service.files().create(body=file_metadata, media_body=media, fields='id').execute()
    print(f'File ID: {file.get("id")}')

if __name__ == '__main__':
    file_path = 'path_to_your_file.txt'  # アップロードするファイルのパス
    upload_file(file_path)

このコードは、指定されたファイルをGoogle Driveにアップロードします。file_path変数にアップロードしたいファイルのパスを指定してください。また、適切なスコープを設定し、credentials.jsonファイルを作成し、プロジェクトディレクトリに配置する必要があります。

未分類

Posted by ぼっち