PyDrive2
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
- breaking Python 3.7 support was dropped in PyDrive2 version 1.16.0. Users on Python 3.7 or older must upgrade their Python environment to 3.8 or newer.
- gotcha The original PyDrive library is deprecated and unmaintained. Using `pydrive` instead of `pydrive2` will lead to unpatched bugs and compatibility issues, especially with recent Google API changes.
- gotcha Google's deprecation of Out-of-Band (OOB) OAuth flows may affect older authentication methods. `LocalWebserverAuth` is the recommended interactive flow.
- gotcha Versions of `pyOpenSSL` and `cryptography` can cause import or runtime errors due to breaking changes in their APIs. Specific versions have been pinned in PyDrive2 to mitigate this.
- gotcha For persistent authentication that doesn't require re-authorization on every run, you need to ensure a refresh token is obtained. This typically requires setting `access_type='offline'` in your OAuth configuration and persisting credentials (e.g., using `gauth.SaveCredentialsFile()`). Without it, access tokens will expire, requiring re-authentication.
Install
-
pip install PyDrive2 -
pip install PyDrive2[fsspec]
Imports
- GoogleAuth
from pydrive2.auth import GoogleAuth
- GoogleDrive
from pydrive2.drive import GoogleDrive
Quickstart
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']}")