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

2024-04-26 04:47:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

^{pr2}$

Tags: fromhttps文件夹comservicegoogleitemsaccount
1条回答
网友
1楼 · 发布于 2024-04-26 04:47:32

我想提出以下修改。在

修改点:

  • 在脚本中,您使用的是服务帐户。从你的评论,我可以理解你想检索你自己的谷歌驱动器文件。因此,我建议使用OAuth2来处理这种情况,因为服务帐户的驱动器与使用Google帐户登录的驱动器不同。在
  • 关于脚本,为了检索特定文件夹下的所有文件和文件夹,我为此发布了一个库。所以在这里,我想提议。

示例脚本:

下面是使用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,该文件夹包含少量文件和文件夹作为测试运行。在

参考文献:

相关问题 更多 >