Search code examples
pythonpython-2.7metadatagoogle-api-python-client

Accessing folders, subfolders and subfiles using PyDrive (Python)


I have the following code from the PyDrive documentation that allows access to top level folders in my Google Drive. I would like to access all of the folders, subfolders, and files from it. How would I go about doing this (I just started using PyDrive)?

#!/usr/bin/python
# -*- coding: utf-8 -*-
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive


gauth = GoogleAuth()
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication

#Make GoogleDrive instance with Authenticated GoogleAuth instance
drive = GoogleDrive(gauth)

#Google_Drive_Tree = 
# Auto-iterate through all files that matches this query
top_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file in top_list:
    print 'title: %s, id: %s' % (file['title'], file['id'])
    print "---------------------------------------------"

#Paginate file lists by specifying number of max results
for file_list in drive.ListFile({'q': 'trashed=true', 'maxResults': 10}):
    print 'Received %s files from Files.list()' % len(file_list) # <= 10
    for file1 in file_list:
        print 'title: %s, id: %s' % (file1['title'], file1['id'])

I have checked the following page How to list all files, folders, subfolders and subfiles of a Google drive folder , which seemed to be the answer I was looking for but the code is not there anymore.


Solution

  • Your code is absolutely correct. But with the default settings of Pydrive , you have access to only the root level files and folders. Changing oauth_scope in settings.yaml file fixes this issue.

    client_config_backend: settings
    client_config:
    client_id: XXX
    client_secret: XXXX
    
    save_credentials: True
    save_credentials_backend: file
    save_credentials_file: credentials.json
    
    get_refresh_token: True
    
    oauth_scope:
      - https://www.googleapis.com/auth/drive
      - https://www.googleapis.com/auth/drive.metadata