使用Drive v3 API搜索文件夹内文件时q参数报错求助
Hey, I see the problem with your Drive API query—you're missing a crucial detail required by the v3 syntax!
When using the in parents operator in the q parameter, the parent folder ID must be wrapped in single quotes. Your current query doesn't include these quotes, which is why the API is throwing an error.
Fixed Code & Explanation
Here's the corrected version of your code, plus a tweak to handle full pagination (so you don't miss files spread across multiple result pages):
page_token = None while True: response = service.files().list( q="'123456789' in parents", # Added single quotes around the parent ID spaces='drive', fields='nextPageToken, files(id, name)', pageToken=page_token ).execute() for file in response.get('files', []): print('Found file: %s (%s)' % (file.get('name'), file.get('id'))) page_token = response.get('nextPageToken', None) if not page_token: break
Key Fixes Breakdown
- Single Quotes Around ID: The
qparameter now uses'123456789' in parentsinstead of123456789 in parents. This is mandatory for Drive v3 when referencing folder or file IDs in query strings—without quotes, the API interprets the ID as an invalid field name. - Full Pagination Loop: Your original code only fetched the first page of results. The
while Trueloop ensures you iterate through all pages until there are no more results left.
Quick Checks If You Still Run Into Issues
- Verify that the parent ID
123456789is correct and corresponds to a folder the authenticated user has access to. - Double-check that your
serviceobject is authenticated with the right scopes (e.g.,https://www.googleapis.com/auth/drive.readonlyfor read access, orhttps://www.googleapis.com/auth/drivefor full access).
内容的提问来源于stack exchange,提问作者jbra95
相关产品推荐
相关产品推荐

