Python script to list files on your Google Drive and download one of them

CK CK 3788 
Created at  
941 0 0

To obtain a Google Drive file list and download files using Python, you'll need to utilize the Google Drive API. First, create a Google Cloud Platform project and enable the Drive API. Then, download the Google Client Library for Python and authenticate your application using OAuth 2.0. Once authenticated, use the API's files.list method to retrieve a list of files and their metadata. For each file you wish to download, use the files.get method with the download parameter set to True to download the file's content to your local system. Handle the returned data accordingly, potentially saving files based on their names and/or IDs.

Here is a Python script to list files on your Google Drive and download one of them using the Google Drive API. The script uses the google-auth, google-auth-oauthlib, and google-auth-httplib2 libraries along with the googleapiclient.discovery module.

Python script to list files on your Google Drive and download one of them

Step 1: Set Up the Google Drive API

  1. Go to the Google Cloud Console.
  2. Create a new project or use an existing one.
  3. Enable the "Google Drive API" for your project.
  4. Create OAuth 2.0 credentials and download the credentials.json file.

 

Step 2: Install Required Libraries

pip install google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

 

Step 3: Python Script

import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseDownload
import io

# Scopes for Google Drive
SCOPES = ['https://www.googleapis.com/auth/drive.readonly']

def authenticate():
    """
    Authenticate and return a Google Drive service instance.
    """
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        with open('token.json', 'w') as token:
            token.write(creds.to_json())
    return build('drive', 'v3', credentials=creds)

def list_files(service, page_size=10):
    """
    List files in Google Drive.
    """
    results = service.files().list(
        pageSize=page_size, fields="nextPageToken, files(id, name)"
    ).execute()
    items = results.get('files', [])
    if not items:
        print('No files found.')
        return []
    else:
        print('Files:')
        for item in items:
            print(f"{item['name']} ({item['id']})")
        return items

def download_file(service, file_id, file_name):
    """
    Download a file from Google Drive.
    """
    request = service.files().get_media(fileId=file_id)
    file_path = os.path.join(os.getcwd(), file_name)
    with io.FileIO(file_path, 'wb') as fh:
        downloader = MediaIoBaseDownload(fh, request)
        done = False
        while not done:
            status, done = downloader.next_chunk()
            print(f"Download {int(status.progress() * 100)}%.")
    print(f"File downloaded to {file_path}")

def main():
    service = authenticate()
    files = list_files(service)
    if files:
        # Select a file to download
        file_id = files[0]['id']  # Replace with the desired file ID
        file_name = files[0]['name']
        download_file(service, file_id, file_name)

if __name__ == '__main__':
    main()

 

Notes:

  1. Save the credentials.json file in the same directory as your script.
  2. The script saves a token.json file to cache credentials and avoid repeated logins.
  3. Modify the file_id to download a specific file.
  4. You may need to adjust permissions if the file is private or shared. Ensure the Google Drive account used has access to the file.
Tags Google Drive Google Drive API Python Python Google API Python Google Drive Facebook X
Comments 0
Similar posts
  1. Method to maximize full CPU performance with Python
    317
  2. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  3. Learning about Python Multiprocessing Technique
    592
  4. Simple Example to get the total number of records in BigQuery with Python
    666
  5. How to run Python 3.9 on Mac?
    652
  6. Implementing a Versatile DNS Server in Python: Handling A, AAAA, CNAME, and TXT Records
    1,071
  7. Building a Basic DNS Server in PHP/Python: A Beginner's Guide
    739
  8. Dynamic DNS Made Easy: Building a Python-Based Solution
    795
  9. Is PyTorch Dead? Deep Learning's Enduring Role Beyond LLMs & Essential Skills
    694
  10. Forecasting with Linear Regression and KNN Regression in Python
    925
  11. Mastering Model Persistence: Saving and Loading Trained Machine Learning Models in Python
    1,156
  12. Harnessing the Power of Random Forest Algorithm in Python
    658
  13. Understanding and Implementing K-Nearest Neighbors (KNN) Algorithm in Python
    633
  14. Python Implementation of Linear Regression
    840
  1. How to install python 3.9 alongside python 3.8 on CentOS 7?
    710
  2. How to run Python 3.9 on Mac?
    652
  3. Python Quizs
    501
  4. Automated OpenAPI documentation for a Python Flask API
    1,120
  5. Automated API documentation for a Django REST Framework (DRF) project using drf-yasg (Yet Another Swagger Generator)
    1,029
  6. Uploading a file to a Google Drive Folder programmatically with Python
    3,307
  7. Garbage Collection when your system does not have enough memory in your Python App
    1,011
  8. Method to maximize full CPU performance with Python
    317
  9. How do I get the maximum available of thread in python?
    990
  10. Using Queue Algorithm with Redis - RPUSH and LPOP
    770
  11. Use cache concept with Redis : Let's do Redis programming with Python
    531
  12. Installing Python 3.8 in a venv environment on CentOS 7
    463
  13. CUDA versus OpenCL
    578
  14. Simple gRPC server based on Python
    394
  15. Python code to convert PDF file to Excel Spreadsheet
    700
  16. Coinbase Python API - Basic Example
    462
  17. AWS Lambda Code Example based on Python
    333
  18. Python code using GPU on CentOS with AWS
    1,251
  19. Video Scence Detection with PySceneDetect
    2,320
  20. Python Audio Separation Libraries allowing you to isolate individual tracks
    1,443
  21. Python Version Control for Library Compatibility with pyenv - Downgrading/Upgrading Python Version
    908
  22. Deleting a specific user voice from the original audio track with Python
    548
  23. Creating an MR from the original MP3 audio in Python - Deleting Voice Track from Audio File
    439
  24. Creating mp3 audio file based on the text input with Python
    465
  25. Implementing Text To Speech / Audio with Python3 and pyttsx3
    355
  26. Building Initial Virtual Environment at Python - The first step you should do for Python Programming
    559
  27. Python Simplified Assignment Operators
    533
  28. Trackback module used for Python Threading debugging
    843
  29. Python Flask with simple HTML files to server web pages along with API
    927
  30. Python Flask web server tutorial from the scratch
    622
Recently updated
  1. Why 100% SEO Guarantees Better User Engagement and How to Achieve It in Your Service
    40
  2. Why SPF and DKIM Are Essential for Linux Email Servers?
    34
  3. How do I create animated background for Google Meet?
    20,611
  4. MaxMind GeoLite2 vs. DB-IP Lite vs. ip-api.com: Choosing the Right Free IP Geolocation Solution
    244
  5. Meet Valkey: Why Redis Changed Its License, Why Valkey is Better, and How to Use It as a Drop-in Replacement
    94
  6. How Rogue Web Scrapers Are Stealing My Content and Destroying My Server
    157
  7. Array of arguments passed to script in PHP
    90
  8. Invalid Auction Storms in Ad Tech
    98
  9. Building MRC-Compliant Instrumentation in Ad Tech: Implementation Steps and Key Challenges
    202
  10. The Two Clocks of Ad Server Architecture
    70
  11. Frequency Cap Architecture Overview
    514
  12. Collecting Proof-of-Play from 100,000 Screens
    146
  13. Vector Search in Relational Databases (RDBs): Trends & Usage Environments
    287
  14. What is RedisVL?
    109
  15. Designing a Skill Registry Architecture: Minimize Token Usage and Maximize AI Performance
    230
  16. TPU & GPU Cluster Management Tools
    243
  17. The Concept of Scaffolding in AI Agents
    233
  18. Beyond Static Pipelines: Architecting LLM Multi-Agent Systems for Autonomous Workflow Orchestration
    583
  19. AI-DLC vs. AI-SDLC: Model-Centric vs. System-Centric AI Development
    258
  20. Fine-Tuning Open-Weight LLMs: Training, Licensing, and Deploying Custom Models with Ollama
    339
  21. Inside the Next-Generation Streaming Architecture: Ultra-Low Latency, SGAI, and AI Codecs
    202
  22. Machine Learning: Training vs. Ranking
    221
  23. The Continuous Learning Machine: Designing a Loop That Actually Turns
    222
  24. The Next-Gen Low-Latency Standards: LL-HLS & MoQ
    195
  25. Designing a Data Curation System Around a Vector Database
    220
  26. Extracting Context from Live Video: The Architecture Got Simpler When We Stopped Building Features
    256
  27. The New Ad Stack Behind Live Sports Streaming: Inside SGAI, EABN, and the Standards Race to Fix Live Monetization
    656
  28. Designing MLOps Architectures to Handle Seasonal Data Drift in EV Fleet Models
    195
  29. From 15 to 40+ FPS: Accelerating PyTorch Object Detection on Automotive ECUs
    217
  30. Understanding Data Lineage
    260