PyDrive2 is a Python client for the Google Drive API v3 and an
fsspec-compatible filesystem for Google Drive. Use it to upload, download,
and list files, or open them by URL with fsspec.open(). PyDrive2 wraps
google-api-python-client and is a fork of PyDrive maintained by the
DataChain team.
PyDrive2 2.0 requires Python 3.11 or newer.
python -m pip install PyDrive2To open gdrive:// URLs with fsspec, install the filesystem extra.
python -m pip install 'PyDrive2[fsspec]'Enable the Google Drive API in your Google Cloud project and create an
OAuth client for a desktop app. Save the downloaded JSON as
client_secrets.json in your working directory. Run the following code
and sign in when the browser opens.
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)You can configure authentication in settings.yaml. The
authentication guide also covers service accounts.
The first Upload() creates the file. Call it again on the same object
to save changes to its name or contents.
note = drive.CreateFile({"name": "Hello.txt"})
note.SetContentString("Hello")
note.Upload()
note["name"] = "HelloWorld.txt"
note.SetContentString(note.GetContentString() + " World!")
note.Upload()To upload a local file, pass its path to SetContentFile(). Use the Drive
ID to download it again.
photo = drive.CreateFile()
photo.SetContentFile("hello.png")
photo.Upload()
download = drive.CreateFile({"id": photo["id"]})
download.GetContentFile("downloaded.png")To export an existing Google Doc, replace DOCUMENT_ID with its Drive ID
and specify the export format.
document = drive.CreateFile({"id": "DOCUMENT_ID"})
document.GetContentFile("document.pdf", mimetype="application/pdf")To collect all matching entries in My Drive's root folder, call
GetList() without a page size. To process the same results a page at a
time, iterate over ListFile() directly.
query = "'root' in parents and trashed=false"
entries = drive.ListFile({"q": query}).GetList()
for entry in entries:
print(entry["name"], entry["id"])
for page in drive.ListFile({"q": query, "pageSize": 10}):
for entry in page:
print(entry["name"], entry["id"])Reuse the authenticated gauth object to read the note created above by
ID. You can also open a named path such as gdrive://root/HelloWorld.txt
or list a folder through the GDriveFileSystem interface.
import fsspec
with fsspec.open(f"gdrive://{note['id']}", "rt", google_auth=gauth) as stream:
print(stream.read()) # Hello World!
fs = fsspec.filesystem("gdrive", google_auth=gauth)
print(fs.ls("root"))PyDrive2 uses a separate HTTP transport for each thread. When using the Drive client concurrently, create a separate file object or listing iterator in each worker.
Thanks to all our contributors!

