问题
I'm trying to find the path of a file when fetching a file list with the Google Drive API.
Right now, I'm able to fetch file properties (currently only fetching checksum, id, name, and 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 (parameters fed to the list() method)
Files documentation (properties returned with each file)
回答1:
- You want to retrieve a folder tree from a file in own Google Drive.
- You want to retrieve the file path. So in your case, it retrieves a parent folder above each file and folder.
- You want to achieve this using google-api-python-client with python.
- You have already been able to get the file metadata using Drive API.
If my understanding is correct, how about this sample script? Unfortunately, in the current stage, the folder tree of the file cannot directly be retrieved by the Google API. So it is required to prepare a script for achieving it. Please think of this as just one of several answers.
Sample script:
This sample script retrieves the folder tree of the file. When you use this script, please set the file 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)
Result:
In the case that the file has the three-layer structure, when you run the script, the following object is returned.
[
{
"id": "folderId3",
"name": "folderName3"
},
{
"id": "folderId2",
"name": "folderName2"
},
{
"id": "folderId1",
"name": "My Drive" # This is the root folder.
}
]
- The 1st element is the bottom layer.
Note:
- In this script, from OP's situation which want to retrieve "the file path", it supposes that each file has only one parent. At the file system of Google Drive, each file can have multiple parents. If in your situation, there are several files which have the multiple parents, this script returns the 1st element of the array of
parents
. Please be careful this. This is also mentioned by pinoyyid's comment.
Reference:
- Files: get
- getfilelistpy
- As another sample, there is a library for retrieving the folder tree from the Google Drive.
来源:https://stackoverflow.com/questions/57618533/google-drive-api-how-can-i-find-the-path-of-a-file