pythongoogle-drive-apigoogle-colaboratorygoogle-api-python-clientservice-accounts

Getting FolderID and folder name inside a particular folder in Google Drive


I am using Colab in Python to get the folder ID and folder name inside a particular folder called myProject from Google Drive.

Folder structure is like this:

Google Drive (When I open drive.google.com I see the below folder structure)
   myProject
    ImageToDoc
        images

I have mounted the drive and it said successful.

But I always get "No folder id and Foldername". I know there are folders and files, the name of the folder is correct too.

this is the code I am trying:

from googleapiclient.discovery import build
from google.oauth2 import service_account
import os

json_key_path = '/content/drive/My Drive/myProject/credentials.json'

if not os.path.exists(json_key_path):
    print("JSON key file not found.")
    exit()

credentials = service_account.Credentials.from_service_account_file(json_key_path)

drive_service = build('drive', 'v3', credentials=credentials)

def get_folder_id_by_name(folder_name, parent_folder_id='root'):
    response = drive_service.files().list(
        q=f"name='{folder_name}' and mimeType='application/vnd.google-apps.folder' and '{parent_folder_id}' in parents",
        fields='files(id)').execute()
    items = response.get('files', [])
    if items:
        return items[0]['id']
    else:
        return None

def list_folders_in_my_project():
  
    my_project_folder_id = get_folder_id_by_name("myProject", parent_folder_id='root')
    print("myProjectfolder ID:", my_project_folder_id)
    
    if not my_project_folder_id:
        print("myProject folder not found.")
        return
    
    response = drive_service.files().list(
        q=f"'{my_project_folder_id}' in parents and mimeType='application/vnd.google-apps.folder'",
        fields='files(name)').execute()
    
    print("API Response:", response)
    
    folders = response.get('files', [])
    if folders:
        print("Folders inside myProject folder:")
        for folder in folders:
            print(f"Folder Name: {folder['name']}")
    else:
        print("No folders found inside myProject folder.")

list_folders_in_my_project()

I am not sure what could be wrong with the above code. Can someone help me fix this?

Thanks!


Solution

  • Google Drive (When I open drive.google.com I see the below folder structure)
    myProject
    ImageToDoc
    images

    Sounds like you are opening the google drive web application from your own account.

    However your code says you are using a service account

    credentials = service_account.Credentials.from_service_account_file(json_key_path)
    

    Have you shared the directory with your service account? If not then it doesnt have access and it cant see them. Just like I couldnt see it if i searched for it.

    Google drive and colab

    Tbh I'm not sure why you are using a service account with colab anyway. Unless you really want to go though the Google drive api in which case your all set.

    You can just mount your google drive account in colab

    from google.colab import drive
    drive.mount('/content/drive')
    DRIVE_PREFIX = "/content/drive/MyDrive"