πŸ“šUpload file to google drive using python

πŸ“šUpload file to google drive using python

Upload Files to Google Drive Using Python

πŸ“Ή Video Tutorial

https://youtu.be/ZL_9gqxAdok

πŸ“‹ Prerequisites

  1. βœ… Google Account
  2. βœ… Python + IDE (VS Code recommended)
  3. βœ… Basic Python knowledge

πŸ” Part 1: Setting Up Google Drive API

Step 1: Enable Google Drive API

1. Go to: Google Drive API Console

2. Create a new project or select an existing one

3. Click Continue to enable the API

Step 2: Configure OAuth Consent Screen

1. Navigate to OAuth Consent Screen

2. Enter your application name and email address

3. Click Save

Step 3: Create OAuth Client ID

1. Go to Credentials tab

2. Click Create Credentials β†’ OAuth client ID

3. Select Desktop app as application type

4. Download the JSON file

5. Rename it to client_secrets.json

βœ… Success! You now have Google Drive API enabled and credentials downloaded.

πŸ’» Part 2: Python Implementation

Step 1: Install Required Packages

πŸ“¦ Installation Commands
pip install --upgrade google-api-python-client
pip install --upgrade oauth2client

Step 2: Organize Your Files

Place these files in the same folder:

  • πŸ“„ client_secrets.json (OAuth credentials)
  • πŸ–ΌοΈ marearts.png (or any file you want to upload)
  • 🐍 upload_to_drive.py (Python script below)

Step 3: Python Upload Script

🐍 upload_to_drive.py - Complete Script
"""
Google Drive File Upload Script
Automatically uploads files to Google Drive using OAuth2 authentication
"""

from googleapiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# Define API scope
SCOPES = 'https://www.googleapis.com/auth/drive.file'

# Load credentials from storage
store = file.Storage('storage.json')
creds = store.get()

# If no valid credentials, authenticate user
if not creds or creds.invalid:
    print("Creating new storage data file...")
    flow = client.flow_from_clientsecrets('client_secrets.json', SCOPES)
    creds = tools.run_flow(flow, store, flags) \
            if flags else tools.run(flow, store)

# Build Google Drive service
DRIVE = build('drive', 'v3', http=creds.authorize(Http()))

# List of files to upload
FILES = (
    'marearts.png',
)

# Upload each file
for file_title in FILES:
    file_name = file_title
    
    # Set file metadata
    metadata = {
        'name': file_name,
        'mimeType': None
    }

    # Upload file to Google Drive
    res = DRIVE.files().create(body=metadata, media_body=file_name).execute()
    
    if res:
        print('Uploaded "%s" (%s)' % (file_name, res['mimeType']))
        print('File ID:', res['id'])

Step 4: First-Time Authentication

When you run the script for the first time:

  1. 🌐 A browser window will open automatically
  2. πŸ” Log in to your Google account
  3. βœ… Grant the requested permissions
  4. πŸ’Ύ A storage.json file will be created (save this!)

Step 5: Run the Script

⚑ Execute the Script
python upload_to_drive.py

🎯 How It Works

Step Description Files Generated
1. Setup Enable API and download credentials client_secrets.json
2. First Run Authenticate via browser storage.json
3. Subsequent Runs Automatic authentication using storage.json -
4. Upload Files uploaded to Google Drive Files in Drive

πŸš€ Advanced Usage

Upload Multiple Files

🐍 Multiple Files Example
FILES = (
    'marearts.png',
    'document.pdf',
    'report.docx',
    'data.csv',
)

Upload to Specific Folder

🐍 Upload to Folder
# Specify folder ID in metadata
metadata = {
    'name': file_name,
    'parents': ['YOUR_FOLDER_ID_HERE'],  # Add folder ID
    'mimeType': None
}

πŸ” Troubleshooting

Issue Solution
Authentication fails Delete storage.json and re-authenticate
File not found error Check file path and ensure it's in same directory
Permission denied Verify OAuth consent screen configuration
Module not found Run pip install commands again

✨ Key Benefits

  • πŸ”„ Automated uploads: No manual dragging and dropping
  • πŸ” Secure authentication: OAuth2 protocol
  • ⚑ Reusable credentials: storage.json for future uploads
  • πŸ“ Batch uploads: Upload multiple files at once
  • πŸ”§ Programmable: Integrate into your workflows
  • β˜• Tea time automation: Set it and forget it!

πŸ“š Resources

πŸŽ‰ Success!

You can now upload files to Google Drive programmatically. Use storage.json for future uploads without re-authentication.

Enjoy your tea time! β˜•οΈ

πŸ™‡πŸ» Thank you!

Β 

Β 

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.