In a list of files I get with the Google Drive API in Python I'm wondering how to determine if an entry is a file or a folder.
I'm listing all files that are on my Google Drive and that are shared with a service account in python:
service = get_service(
api_name='drive',
api_version='v3',
scopes=[scope],
key_file_location=key_file_location)
# Call the Drive v3 API
results = service.files().list(
pageSize=1000, fields="nextPageToken, files(kind, id, name, size, parents, sha256Checksum, version, modifiedTime)").execute()
items = results.get('files', [])
This works but in the documentation I could not find a clean way to determine if an entry is a file oder a "folder". I noticed that folders have no size and e.g. no sha256Checksum but there might be other objects that dont't have these.
What would be the correct way to determine if an entry in the resulting list is a file or a "folder"?
I believe your goal is as follows.
items in your script, you want to separate the values to the files and the folders.In this case, how about using mimeType? The mimeType of the folder on Google Drive is application/vnd.google-apps.folder. I thought that this might be able to be used for achieving your goal. When this is reflected in your script, it becomes as follows.
results = service.files().list(
pageSize=1000, fields="nextPageToken, files(kind, id, name, size, parents, sha256Checksum, version, modifiedTime)").execute()
items = results.get('files', [])
results = service.files().list(pageSize=1000, fields="nextPageToken, files(kind, id, name, size, parents, sha256Checksum, version, modifiedTime, mimeType)").execute()
items = results.get("files", [])
obj = {"files": [], "folders": []}
for e in items:
if e["mimeType"] == "application/vnd.google-apps.folder":
obj["folders"].append(e)
else:
obj["files"].append(e)
print(obj)
When this script is run, obj is {"files": [,,,], "folders": [,,,]}. By this, the retrieved values can be separated into files and folders.
If you want to retrieve only folders, I think that in this case, the search query can be used as follows.
results = service.files().list(pageSize=1000, fields="nextPageToken, files(kind, id, name, size, parents, sha256Checksum, version, modifiedTime, mimeType)", q="mimeType='application/vnd.google-apps.folder' and trashed=false").execute()
items = results.get("files", [])
print(items)
And, if you want to retrieve only files except for folders, also I think that in this case, the search query can be used as follows.
results = service.files().list(pageSize=1000, fields="nextPageToken, files(kind, id, name, size, parents, sha256Checksum, version, modifiedTime, mimeType)", q="mimeType!='application/vnd.google-apps.folder' and trashed=false").execute()
items = results.get("files", [])
print(items)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With