| To upload a file to a Google Drive folder programmatically, you need to use the Google Drive API. Below is an example of Python code to upload a file to a specific folder in Google Drive. Steps to Follow:
Set Up Google Drive API: - Go to the Google Cloud Console.
- Create a new project (or use an existing one).
- Enable the "Google Drive API" for your project.
- Create credentials for a "Desktop App" and download the
credentials.json file.
Install the Required Libraries: Install the google-auth, google-auth-oauthlib, and googleapiclient Python libraries: pip install google-auth google-auth-oauthlib googleapiclient
Code for Uploading a File: from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
import os
# Path to your credentials.json file
CREDENTIALS_FILE = 'credentials.json'
SCOPES = ['https://www.googleapis.com/auth/drive.file']
def authenticate_google_drive():
# Check if token.json exists
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
else:
from google_auth_oauthlib.flow import InstalledAppFlow
flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for future use
with open('token.json', 'w') as token_file:
token_file.write(creds.to_json())
return creds
def upload_file_to_drive(file_path, folder_id):
# Authenticate
creds = authenticate_google_drive()
service = build('drive', 'v3', credentials=creds)
# Get the file name
file_name = os.path.basename(file_path)
# Set up the file metadata
file_metadata = {
'name': file_name,
'parents': [folder_id] # Specify the folder ID
}
# Upload the file
media = MediaFileUpload(file_path, resumable=True)
uploaded_file = service.files().create(
body=file_metadata,
media_body=media,
fields='id'
).execute()
print(f"File uploaded successfully! File ID: {uploaded_file.get('id')}")
# Example usage
file_to_upload = 'example.txt' # Path to your file
drive_folder_id = 'your-folder-id' # Replace with the target Google Drive folder ID
upload_file_to_drive(file_to_upload, drive_folder_id)
Key Points:- Replace
'example.txt' with the file path you want to upload. - Replace
'your-folder-id' with the folder ID of the target Google Drive folder.- You can find the folder ID in the URL of the Google Drive folder:
https://drive.google.com/drive/folders/<folder-id>.
Authentication Notes:- The first time you run the script, it will open a browser to authenticate with your Google account and generate a
token.json file. Future runs will use this file for authentication. |