使用 python api 显示 google 驱动器中的子文件夹

showing subfolders in google drive using python api

我正在尝试列出 google 驱动器中的所有文件夹(和子文件夹)。

我的根文件夹中有六个子文件夹。但我的代码只显示文件。

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 版本。它允许浏览器创建一个token,然后应该运行,但是创建token后,它执行时冻结:

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)

我想提出以下修改。

修改点:

  • 在您的脚本中,您使用的是服务帐户。从您的评论中,我了解到您想检索自己的 Google 云端硬盘中的文件。所以我建议针对这种情况使用 OAuth2,因为 Drive of Service Account 与您使用 Google 帐户登录的 Drive 不同。
  • 关于脚本,为了检索特定文件夹下的所有文件和文件夹,我为此发布了一个库。所以在这里,我想提出来。

示例脚本:

使用OAuth2 的示例脚本如下。在此示例脚本中,OAuth2 的进程使用 the quickstart of Google。请在 运行 脚本之前检查此项。

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('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)

resource = {
    "oauth2": creds.authorize(Http()),
    "id": "### Folder ID ###",
    "fields": "files(name,id)",
}
res = getfilelist.GetFileList(resource)  # or r = getfilelist.GetFolderTree(resource)
print(res)
  • 如果您不使用 "id": "### Folder ID ###",将检索自己的 Google 驱动器中的所有文件。所以当你的驱动器中有很多文件时,它会花费很长时间。所以一开始,请使用文件和文件夹数量较少的文件夹的特定文件夹ID作为测试运行。

参考文献: