Get folder id by folder name

142 Views Asked by At

I would like to find folder_id by using a folder name to search in your Google Drive.

Error: <HttpError 404 when requesting https://www.googleapis.com/drive/v2/files?q=%27None%27+and+trashed%3Dfalse&maxResults=1000&supportsAllDrives=true&includeItemsFromAllDrives=true&alt=json returned "File not found:". Details: "[{'message': 'File not found: ', 'domain': 'global', 'reason': 'notFound', 'location': 'file', 'locationType': 'other'}]">

Here is my current part of the script that fails. I start to wonder if it is even possible to search for a certain folder by name.

def get_folder_id_by_name(self, drive, folder_name):
        file_list = drive.ListFile({'q': "mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
        for file in file_list:
            if file['title'] == folder_name:
                return file['id']
            return None

if not self.backup:
    # Use self.options['backup_folder'] as the folder ID where backups are stored
    backup_folder_name = self.options['backup_folder']
    backup_folder_id = self.get_folder_id_by_name(self.drive, backup_folder_name)

    if not backup_folder_id:
    # If the folder doesn't exist, create it
        folder = self.drive.CreateFile({'title': backup_folder_name, 'mimeType': 'application/vnd.google-apps.folder'})
        folder.Upload()
        backup_folder_id = folder['id']
        print(f"Created folder '{backup_folder_name}' with ID: {backup_folder_id}")
1

There are 1 best solutions below

7
Tanaike On

I think that in order to search the folder using the folder name, the folder name can be included in the search query. So, in your script, how about the following modification?

From:

def get_folder_id_by_name(self, drive, folder_name):
        file_list = drive.ListFile({'q': "mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
        for file in file_list:
            if file['title'] == folder_name:
                return file['id']
            return None

To:

def get_folder_id_by_name(self, drive, folder_name):
    file_list = drive.ListFile(
        {'q': "title='" + folder_name + "' and mimeType='application/vnd.google-apps.folder' and trashed=false"}).GetList()
    if file_list != []:
        return file_list[0]['id']
    return None
  • If you want to search the folder by including the shared drive, please modify it as follows.

    def get_folder_id_by_name(self, drive, folder_name):
        file_list = drive.ListFile(
            {
                'q': "title='" + folder_name + "' and mimeType='application/vnd.google-apps.folder' and trashed=false",
                'corpora': 'allDrives',
                'includeItemsFromAllDrives': True,
                'supportsAllDrives': True,
            }).GetList()
        if file_list != []:
            return file_list[0]['id']
        return None
    
  • In the case of PyDrive2, title is used for searching the file and folder name because of Drive API v2. Ref

Reference:

Added:

About your following reply,

Maybe I forgot to include: The folder it is searching for does NOT exist, so it has to create the folder. I know it can find the folder if I manually create it in my Google Drive.

I couldn't notice about this from your question. So, if you want to create a new folder when the folder name does not exist, how about the following modification?

def get_folder_id_by_name(self, drive, folder_name):
    file_list = drive.ListFile(
        {
            'q': "title='" + folder_name + "' and mimeType='application/vnd.google-apps.folder' and trashed=false",
            'corpora': 'allDrives',
            'includeItemsFromAllDrives': True,
            'supportsAllDrives': True,
        }).GetList()
    if file_list != []:
        return file_list[0]['id']
    folder = drive.CreateFile({'title': folder_name, "mimeType": "application/vnd.google-apps.folder"})
    folder.Upload()
    return folder['id']
  • When this script is run with folder_name, when the folder name is not existing, a new folder is created. From your reply and question, I couldn't know the parent folder you want to create. So, in this case, the new folder is created in the root folder.

  • If you want to create a new folder in the specific parent folder, please modify it as follows.

    folder = drive.CreateFile({'title': folder_name, "parents": [{"id": "### parent folder ID ###"}], "mimeType": "application/vnd.google-apps.folder"})