使用PyDrive(Python)访问文件夹,子文件夹和子文件


问题内容

我有PyDrive文档中的以下代码,该代码允许访问Google云端硬盘中的顶级文件夹。我想从中访问所有文件夹,子文件夹和文件。我将如何做(我刚刚开始使用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'])

我已经检查了以下页面如何列出Google驱动器文件夹的所有文件,文件夹,子文件夹和子文件,这似乎是我正在寻找的答案,但是代码不再存在。


问题答案:

您的代码绝对正确。但是,使用Pydrive的默认设置,您只能访问根级别的文件和文件夹。更改settings.yaml文件中的oauth_scope可解决此问题。

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