Created
September 10, 2024 03:19
-
-
Save PramodDutta/a99b8f7d970e6b7e9d0416c897eb956b to your computer and use it in GitHub Desktop.
Code to upload a doc to Drive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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