pythongoogle-drive-api

Passing a variable to a query in google-drive-api files().list function


I'm trying to create a function which takes in a directory name as a parameter and returns the ID of the directory. The ultimate goal is to list the files in said directory using the returned file ID, however I can't seem to figure out the syntax for passing the directory name in as a variable.

I can only manage to do something of the following, where I need to explicitly type in the name of the directory. Please note that I am using v3 of the google drive api.

def get_folder_id():

    folder_ID = ""

    while True:
        response = drive_service.files().list(
            q="name='folder1'", fields="nextPageToken, files(id,name)").execute()

        files = response.get('files', [])

        for item in files:
            print ("Found file: %s, %s" % (item['name'], item['id']))
            folder_ID = item['id']

        page_token = response.get('nextPageToken', None)

        if page_token == None:
            break

    return folder_ID

How can I pass the folder name as a parameter and still include it in the q query?

I've tried variants such as:

response = drive_service.files().list(
            q='"name="' + "'" + f_name + "'" + '"', fields="nextPageToken, files(id,name)").execute()

In an attempt to include the single quotes around the request, but this doesn't work either


Solution

  • If my understanding is correct, how about using the following search query? Please modify as follows.

    From:

    q='"name="' + "'" + f_name + "'" + '"'
    

    To:

    q="name='" + f_name + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"
    

    By above search query, the folders which has the folder name of f_name are retrieved.

    Reference:

    If I misunderstood your question and this was not the result you want, I apologize.