Google 驱动器 API 如何找到文件的路径?

Google Drive API How can I find the path of a file?

我在使用 Google 驱动器 API 获取文件列表时试图找到文件的路径。

现在,我可以获取文件属性(目前只能获取校验和、id、名称和 mimeType):

results = globalShares.service.files().list(pageSize=1000,corpora='user',fields='nextPageToken, files(md5Checksum, id, name, mimeType)').execute()
items = results.get('files',[])
nextPageToken = results.get('nextPageToken',False)
for file in items:
    print("===========================================================")
    pp.pprint(file)
print(str(len(items)))
print(nextPageToken)

List documentation(传递给 list() 方法的参数)

Files documentation(随每个文件返回的属性)

  • 您想从自己的 Google 驱动器中的文件中检索文件夹树。
    • 您想检索文件路径。因此,在您的情况下,它会在每个文件和文件夹上方检索一个父文件夹。
  • 您想使用 google-api-python-client 和 python.
  • 来实现此目的
  • 您已经能够使用驱动器 API 获取文件元数据。

如果我的理解是正确的,这个示例脚本怎么样?不幸的是,在现阶段,文件的文件夹树无法通过 Google API 直接检索。所以需要准备一个脚本来实现它。请将此视为几个答案之一。

示例脚本:

此示例脚本检索文件的文件夹树。使用本脚本时,请设置文件ID。

fileId = '###'  # Please set the file ID here.

tree = []  # Result
file = globalShares.service.files().get(fileId=fileId', fields='id, name, parents').execute()
parent = file.get('parents')
if parent:
    while True:
        folder = service.files().get(
            fileId=parent[0], fields='id, name, parents').execute()
        parent = folder.get('parents')
        if parent is None:
            break
        tree.append({'id': parent[0], 'name': folder.get('name')})

print(tree)

结果:

在文件具有三层结构的情况下,当您运行脚本时,返回以下对象。

[
  {
    "id": "folderId3",
    "name": "folderName3"
  },
  {
    "id": "folderId2",
    "name": "folderName2"
  },
  {
    "id": "folderId1",
    "name": "My Drive"  # This is the root folder.
  }
]
  • 第一个元素是底层。

注:

  • 在这个脚本中,从OP要检索"the file path"的情况来看,它假设每个文件只有一个父文件。在 Google 驱动器的文件系统中,每个文件可以有多个父文件。如果在您的情况下,有多个文件具有多个父级,则此脚本 returns parents 数组的第一个元素。请注意这一点。 .
  • 也提到了这一点

参考: