我从 Google 开发者网站获取了这段代码,并对其进行了一些更改。但我想要搜索 Google 云端硬盘中存在的文件。我不知道在哪里提供文件夹 ID
来查找文件?如果它们存在,则好的,文件已找到
消息。如果没有,则找不到文件
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
SCOPES = ['https://www.googleapis.com/auth/drive']
def main():
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
with open('token.json', 'w') as token:
token.write(creds.to_json())
service = build('drive', 'v3', credentials=creds)
filename = 'Image'
page_token = None
while True:
response = service.files().list(q="name contains '"+filename+"'",
spaces='drive',
fields='nextPageToken, files(id, name)',
pageToken=page_token).execute()
for file in response.get('files', []):
# Process change
print('Found file: %s (%s)' % (file.get('name'), file.get('id')))
page_token = response.get('nextPageToken', None)
if page_token is None:
break
if __name__ == '__main__':
main()
最佳答案
I want is to search for the files that are present in Google drive.
执行普通的 file.list 将返回 Google 驱动器根目录中的所有文件,没有特殊顺序。
I don't know where to give the folder id to find the files?.
要搜索特定文件夹中的所有文件,您需要使用 Q 搜索参数的 parents in
选项。
response = service.files().list(q="parents in '"+ Folder ID +"'",
spaces='drive',
fields='nextPageToken, files(id, name)',
pageToken=page_token).execute()
我建议执行如下操作,首先搜索文件夹,这将帮助您找到可以在上面的请求中使用的文件夹的文件 ID。
response = service.files().list(q="name = '"+ folder name +"' and mimeType = 'application/vnd.google-apps.folder'",
spaces='drive',
fields='nextPageToken, files(id, name)',
您可能想查看Search for files and folders它有一些有趣的例子。
If they exist then okay, the files are found message. If not then files are not found
如果您正在搜索特定的文件名,并且该名称不存在,您可能会从 API 返回空响应而不是错误。因此,只需测试是否有任何文件返回即可告诉您是否找到了这些文件。
关于python - 如何在Google Drive中搜索特定文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66914793/