Excluding folders starting with a dot in google drive API query

92 Views Asked by At

I am using Python client for google drive API.

I want to enumerate folders that has a name that does not start with a dot ('.').

My naive query to find the folders looks like this:

query = f"""
    {root_folder_id}' in parents
    and mimeType = '{FOLDER_MIMETYPE}'
    and trashed = false
    and not name contains '.'
    """

The reason I used the contains operator here is because it is stated in the official documentation quote:

The contains operator only performs prefix matching for a name term. For example, suppose you have a name of HelloWorld. A query of name contains 'Hello' returns a result, but a query of name contains 'World' doesn't.

My query does not work. It does not find any folders. If I remove the offending last part and not name contains '.' then it finds all folders, including those with a dot at the start of the name, so I have narrowed it down to this part.

How can I solve this?

1

There are 1 best solutions below

0
On

Suggestion:

You can try this other approach to enumerate folders that have a name that does not start with a dot ('.').

Fetch all the folders from a parent folder and then filter the result using python list comprehension to get all folders that do not start with dot.

Code

from google.colab import auth
from google.auth import default
from googleapiclient.discovery import build

#Authentication
auth.authenticate_user()
creds, _ = default()
drive_service = build('drive', 'v3', credentials=creds)

# Set the parent folder ID
parent_folder_id = PARENT_FOLDER_ID_HERE

# Retrieve all folders from the specified parent folder
query = f"'{parent_folder_id}' in parents and mimeType='application/vnd.google-apps.folder' and trashed = false"
results = drive_service.files().list(q=query).execute()
folders = results.get('files', [])
# Filter folders based on the criteria (no "." in the name)
filtered_folders = [folder for folder in folders if '.' not in folder['name']]

# Print the names of the folders that match the criteria
for folder in filtered_folders:
    print(f"Folder Name: {folder['name']}")

NOTE: We may differ on the authentication part of the code since I am using google Colaboratory on running this code

Output:

image

Parent Folder on Google Drive:

image

References:

List Comprehension

Method: files.list