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

Folder structure is like this:

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

我已安装驱动器,它说成功.

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

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

我不知道上面的代码有什么问题.有人能帮我解决这个问题吗?

谢谢!

推荐答案

Google Drive(当我打开drive.google.com时,我看到以下文件夹 struct )
我的项目
ImageToDoc
图片

听起来像是你正在从自己的帐户打开谷歌驱动器Web应用程序.

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

credentials = service_account.Credentials.from_service_account_file(json_key_path)

您是否与您的服务帐户共享目录? 如果没有,那么它就没有访问权限,也看不到它们. 就像我找不到它一样.

Google drive and colab

tbh我不知道你为什么要使用colab的服务帐户.除非你真的想通过谷歌驱动器api在这种情况下你的所有设置.

您可以在colab安装您的谷歌驱动器帐户

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

Python相关问答推荐

acme错误-Veritas错误:模块收件箱没有属性linear_util'

Django管理面板显示字段最大长度而不是字段名称

替换字符串中的多个重叠子字符串

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

如何在箱形图中添加绘制线的传奇?

Django mysql图标不适用于小 case

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

优化pytorch函数以消除for循环

如何更改分组条形图中条形图的 colored颜色 ?

从一个系列创建一个Dataframe,特别是如何重命名其中的列(例如:使用NAs/NaN)

pandas:排序多级列

索引到 torch 张量,沿轴具有可变长度索引

lityter不让我输入左边的方括号,'

使用Python查找、替换和调整PDF中的图像'

OpenGL仅渲染第二个三角形,第一个三角形不可见

删除特定列后的所有列

如何使用pytest在traceback中找到特定的异常

如何防止html代码出现在quarto gfm报告中的pandas表之上

将像素信息写入文件并读取该文件

Pandas:使列中的列表大小与另一列中的列表大小相同