如何使用python检查名称中的文件夹是否存在于Google驱动器中?
我尝试使用以下代码:
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)
答案 0 :(得分:1)
requests.get()
来实现。如果我的理解是正确的,那么该修改如何?请认为这只是几个答案之一。
name='filename' and mimeType='application/vnd.google-apps.folder'
and trashed=false
。files
的属性。此属性是一个数组。如果该文件夹存在,则该数组包含元素。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.
如果我误解了您的问题,请告诉我。我想修改它。
答案 1 :(得分:0)
关于如何检查目标文件夹是否存在并返回其ID,您可能会看到此sample code。
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']
还可以通过此tutorial检查文件夹是否存在,如果不存在,则使用给定名称创建一个文件夹。