PyDrive2

1.21.3 · active · verified Sun Apr 12

PyDrive2 is an actively maintained fork of PyDrive, a Python wrapper library for the Google Drive API. It simplifies common Google Drive API tasks like authentication and file management, providing an object-oriented interface. The library is currently at version 1.21.3 and has a regular release cadence, with recent updates addressing dependency compatibility and new features like fsspec integration.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to authenticate with Google Drive using `PyDrive2` and then upload a simple text file. It utilizes `LocalWebserverAuth` for initial authorization and saves credentials for subsequent runs. Ensure you have downloaded your `client_secrets.json` from the Google API Console and placed it in your working directory. You must enable the Google Drive API for your project in the Google Cloud Console.

import os
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive

# IMPORTANT: Place your 'client_secrets.json' file in the same directory
# as this script, or specify its path in gauth.settings['client_config_file'].
# Instructions to get client_secrets.json: https://docs.iterative.ai/PyDrive2/quickstart/#authentication

gauth = GoogleAuth()
# Uncomment the following line to specify a custom path for client_secrets.json
# gauth.settings['client_config_file'] = os.path.join(os.getcwd(), 'path_to_your', 'client_secrets.json')

# Try to load saved client credentials
try:
    gauth.LoadCredentialsFile("mycreds.txt")
except Exception:
    pass # File might not exist yet

if gauth.credentials is None:
    # Authenticate if credentials are not found or invalid.
    # For persistent access, ensure your OAuth client is configured for 'offline' access
    # to receive a refresh token. This requires manual setup in Google Cloud Console.
    gauth.LocalWebserverAuth() 
elif gauth.access_token_expired:
    # Refresh credentials if the access token has expired
    gauth.Refresh()
else:
    # Authorize with the loaded credentials
    gauth.Authorize()

# Save the current credentials to a file for future use
gauth.SaveCredentialsFile("mycreds.txt")

drive = GoogleDrive(gauth)

# Create a text file and upload it to Google Drive
file_title = "MyTestFile_PyDrive2.txt"
file_content = "Hello, Google Drive from PyDrive2!"

file = drive.CreateFile({'title': file_title})
file.SetContentString(file_content)
file.Upload()
print(f"Uploaded file: {file['title']} (ID: {file['id']})")

# List files in the root folder of Google Drive
print("\nFiles in Google Drive (first 10):")
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for f in file_list:
    print(f"Title: {f['title']}, ID: {f['id']}")

view raw JSON →