Skip to content

Instantly share code, notes, and snippets.

@PramodDutta
Created September 10, 2024 03:19
Show Gist options
  • Save PramodDutta/a99b8f7d970e6b7e9d0416c897eb956b to your computer and use it in GitHub Desktop.
Save PramodDutta/a99b8f7d970e6b7e9d0416c897eb956b to your computer and use it in GitHub Desktop.
Code to upload a doc to Drive
import os
import io
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
# Set up the Drive API
SCOPES = ['https://www.googleapis.com/auth/drive.file']
SERVICE_ACCOUNT_FILE = 'path/to/credentials.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
service = build('drive', 'v3', credentials=credentials)
def upload_file(file_path):
try:
# Check if the file exists
if not os.path.exists(file_path):
raise FileNotFoundError(f"The file {file_path} was not found.")
# Prepare the file for upload
file_metadata = {
'name': os.path.basename(file_path),
'mimeType': 'application/vnd.google-apps.document' # Specify Google Docs MIME type
}
media = MediaFileUpload(file_path, mimetype='text/plain')
# Upload the file
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
print(f"File uploaded successfully. File ID: {file.get('id')}")
except FileNotFoundError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
upload_file('path/to/your/file.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment