获取Google Drive中特定文件夹内的FolderID和文件夹名称

问题描述 投票:0回答:1

我在 Python 中使用 Colab 从 Google Drive 获取名为 myProject 的特定文件夹内的文件夹 ID 和文件夹名称。

文件夹结构是这样的:

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

我已经安装了驱动器并且显示成功。

但我总是得到“没有文件夹 ID 和文件夹名称”。我知道有文件夹和文件,文件夹的名称也是正确的。

这是我正在尝试的代码:

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()

我不确定上面的代码有什么问题。有人可以帮我解决这个问题吗?

谢谢!

python google-drive-api google-colaboratory google-api-python-client service-accounts
1个回答
0
投票

Google Drive(当我打开drive.google.com时,我看到下面的文件夹结构)
我的项目
图像转文档
图片

听起来您正在从自己的帐户打开 Google Drive Web 应用程序。

但是您的代码显示您正在使用服务帐户

credentials = service_account.Credentials.from_service_account_file(json_key_path)

您是否与您的服务帐户共享了目录?如果没有,则它无权访问并且看不到它们。就像我搜索也看不到一样。

© www.soinside.com 2019 - 2024. All rights reserved.