Uploading a file to a Google Drive Folder programmatically with Python

CK CK 3788 
Created at
Updated at  
3,310 0 0

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:

Uploading a file to a Google Drive Folder programmatically with Python

  1. 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.

     

  2. Install the Required Libraries: Install the google-auth, google-auth-oauthlib, and googleapiclient Python libraries:

    pip install google-auth google-auth-oauthlib googleapiclient
    

     

  3. 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.
Tags Google Drive Google Drive API Python Facebook X
Comments 0
Similar posts
  1. Method to maximize full CPU performance with Python
    325
  2. Python script to list files on your Google Drive and download one of them
    941
  3. How to run Python 3.9 on Mac?
    656
  4. Learning about Python Multiprocessing Technique
    594
  5. Simple Example to get the total number of records in BigQuery with Python
    668
  6. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,078
  7. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    747
  8. Dynamic DNS Made Easy: Building a Python-Based Solution
    796
  9. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    699
  10. Forecasting with Linear Regression and KNN Regression in Python
    929
  11. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,166
  12. Harnessing the Power of Random Forest Algorithm in Python
    660
  13. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    636
  14. Python Implementation of Linear Regression
    843
  1. How to Build a Python Chatbot That Writes and Runs Code Using Microsoft AutoGen (With Sample Code)
    244
  2. Beyond Prompt Engineering: Why Loop Engineering is the Future of Autonomous AI
    310
  3. A Python Code to get the Server Instance ID for Remote Management
    366
  4. From Local Python Web to Standalone
    2,056
  5. Demystifying FAISS: Your Guide to ANN(Approximate Nearest Neighbor) Search
    326
  6. TensorRT for LLMs: Speed, Scale, and Why Startups Choose It Over TensorFlow
    467
  7. Python ML Technologies used for the target Segmentation
    381
  8. Managing WHITE_LIST in FastAPI to Improve the Server Security
    355
  9. A common async example
    990
  10. Milvus and LLM Integration - Very Smart Approach!
    304
  11. Automated API Documentation with PyCharm
    896
  12. How to install python 3.9 alongside python 3.8 on CentOS 7?
    719
  13. Python Quizs
    502
  14. Automated OpenAPI documentation for a Python Flask API
    1,127
  15. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,033
  16. Garbage Collection when your system does not have enough memory in your Python App
    1,021
  17. How do I get the maximum available of thread in python?
    995
  18. Using Queue Algorithm with Redis - RPUSH and LPOP
    776
  19. Use cache concept with Redis : Let's do Redis programming with Python
    539
  20. Installing Python 3.8 in a venv environment on CentOS 7
    465
  21. CUDA versus OpenCL
    584
  22. Simple gRPC server based on Python
    398
  23. Python code to convert PDF file to Excel Spreadsheet
    705
  24. Coinbase Python API - Basic Example
    465
  25. AWS Lambda Code Example based on Python
    334
  26. Python code using GPU on CentOS with AWS
    1,258
  27. Video Scence Detection with PySceneDetect
    2,339
  28. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,452
  29. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    913
  30. Deleting a specific user voice from the original audio track with Python
    553
Recently updated
  1. Google OAuth Token Expiration: Causes and Solutions
    31
  2. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    57
  3. Why SPF and DKIM Are Essential for Linux Email Servers?
    51
  4. How do I create animated background for Google Meet?
    23,229
  5. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    273
  6. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    104
  7. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    170
  8. Array of arguments passed to script in PHP
    99
  9. Invalid Auction Storms in Ad Tech
    107
  10. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    208
  11. The Two Clocks of Ad Server Architecture
    78
  12. Frequency Cap Architecture Overview
    527
  13. Collecting Proof-of-Play from 100,000 Screens
    153
  14. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    303
  15. What is RedisVL?
    116
  16. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    247
  17. TPU & GPU Cluster Management Tools
    258
  18. The Concept of Scaffolding in AI Agents
    245
  19. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    598
  20. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    269
  21. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    354
  22. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    207
  23. Machine Learning: Training vs. Ranking
    230
  24. The Continuous Learning Machine: Designing a Loop That Actually Turns
    228
  25. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    203
  26. Designing a Data Curation System Around a Vector Database
    230
  27. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    263
  28. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    674
  29. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    201
  30. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    233