【发布时间】:2019-07-27 07:55:18
【问题描述】:
我正在尝试列出谷歌驱动器中的所有文件夹(和子文件夹)。
我的根文件夹中有六个子文件夹。但我的代码只显示文件。
def credentials_from_file():
"""Load credentials from a service account file
Args:
None
Returns: service account credential object
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
"""
# https://developers.google.com/identity/protocols/googlescopes#drivev3
SCOPES = [
'https://www.googleapis.com/auth/drive'
]
SERVICE_ACCOUNT_FILE = './auth_creds.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
return credentials
credentials = credentials_from_file()
service = discovery.build('drive', 'v3', credentials=credentials)
results = service.files().list(pageSize=10, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
如何让它也告诉我子文件夹? 谢谢!
更新 #1。这是 OAuth 版本。它允许浏览器创建一个令牌,然后应该运行,但在创建令牌后,它会在执行时冻结:
from httplib2 import Http
from oauth2client import file, client, tools
from getfilelistpy import getfilelist
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
store = file.Storage('token.json')
creds = store.get()
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('rrc_crds.json', SCOPES)
creds = tools.run_flow(flow, store)
resource = {
"oauth2": creds.authorize(Http()),
"fields": "files(name,id)",
}
res = getfilelist.GetFileList(resource) # or r = getfilelist.GetFolderTree(resource)
print(res)
【问题讨论】:
-
这个库对你的情况有用吗? github.com/tanaikech/getfilelistpy
-
谢谢。仍然没有显示子文件夹。感谢您的洞察力。是一个很好的名册。
-
感谢您的回复。虽然我不确定我是否能正确理解你的情况,但是这个怎么样?在您的脚本中,您使用的是服务帐户。如果您想在自己的 Google Drive 上检索文件夹列表,请使用 OAuth2,因为 Drive of Service Account 与您使用 Google 帐户登录的 Drive 不同。如果我误解了您的情况,我深表歉意。
-
做到了。我得到了我正在寻找的文件夹。非常感谢!
-
你能把所有这些都总结一下,这样我就可以给你加分回答了?谢谢
标签: python google-drive-api google-api-python-client