Reputation: 115
How to check whether a folder exists in google drive with name using python?
I have tried with the following code:
import requests
import json
access_token = 'token'
url = 'https://www.googleapis.com/drive/v3/files'
headers = {
'Authorization': 'Bearer' + access_token
}
response = requests.get(url, headers=headers)
print(response.text)
Upvotes: 2
Views: 1816
Reputation: 13469
You may see this sample code on how to check if destination folder exists and return its ID.
def get_folder_id(drive, parent_folder_id, folder_name):
"""
Check if destination folder exists and return it's ID
"""
# Auto-iterate through all files in the parent folder.
file_list = GoogleDriveFileList()
try:
file_list = drive.ListFile(
{'q': "'{0}' in parents and trashed=false".format(parent_folder_id)}
).GetList()
# Exit if the parent folder doesn't exist
except googleapiclient.errors.HttpError as err:
# Parse error message
message = ast.literal_eval(err.content)['error']['message']
if message == 'File not found: ':
print(message + folder_name)
exit(1)
# Exit with stacktrace in case of other error
else:
raise
# Find the the destination folder in the parent folder's files
for file1 in file_list:
if file1['title'] == folder_name:
print('title: %s, id: %s' % (file1['title'], file1['id']))
return file1['id']
Also from this tutorial, you can check if folder exists and if not, then create one with the given name.
Upvotes: 0
Reputation: 201603
requests.get()
.If my understanding is correct, how about this modification? Please think of this as just one of several answers.
name='filename' and mimeType='application/vnd.google-apps.folder'
and trashed=false
to the query.files
. This property is an array. If the folder is existing, the array has elements.import requests
import json
foldername = '#####' # Put folder name here.
access_token = 'token'
url = 'https://www.googleapis.com/drive/v3/files'
headers = {'Authorization': 'Bearer ' + access_token} # Modified
query = {'q': "name='" + foldername + "' and mimeType='application/vnd.google-apps.folder'"} # Added
response = requests.get(url, headers=headers, params=query) # Modified
obj = response.json() # Added
if obj['files']: # Added
print('Existing.') # Folder is existing.
else:
print('Not existing.') # Folder is not existing.
If I misunderstood your question, please tell me. I would like to modify it.
Upvotes: 2