Search code examples
pythongoogle-apigoogle-drive-apigoogle-sheets-apigoogle-api-python-client

getting files from google drive from particular folder with Google drive API (Python)


I want to get list all spreadsheets from Google drive by using Google drive API. I have wrote a script in python which is returning me all spreadsheets list from my Google drive but the issue is that this list also contains files (and folders) that are are in bin folder (that i have deleted). I don't want that list. i only want to get list of spreadsheets that are currently in my Google sheets account. Here is my code.

result = drive_service.files().list().execute().get('files', [])

drive_service is service instance that i have created to access user's google drive. It will be also helpful if someone tell that how to get list of files from google drive from only particular folder (like how to get list of all files that are only present in my_drive folder in google drive)


Solution

  • you should look at the q parameter search-files

    The following code would show only the sheets on your drive account.

    response = drive_service.files().list(q="mimeType='application/vnd.google-apps.spreadsheet'",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()
    

    You can add and trashed = false if you dont want to see the files that are in trash.

    response = drive_service.files().list(q="mimeType='application/vnd.google-apps.spreadsheet' and trashed = false",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()
    

    If you want to see only files in a specific folder then you can add parents in 'folder id'

    response = drive_service.files().list(q="mimeType='application/vnd.google-apps.spreadsheet' and trashed = false and parents in 'FolderId'",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()