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

1 投票
1 回答
48 浏览
提问于 2025-04-12 23:45

我在用Python的Colab来获取Google Drive中一个叫myProject的文件夹里的文件夹ID和文件夹名称。

文件夹结构是这样的:

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

我已经成功挂载了Google Drive。

但是我总是收到“No folder id and Foldername”的提示。我知道里面有文件夹和文件,文件夹的名字也没错。

这是我正在尝试的代码:

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

我不太确定上面的代码哪里出了问题。有人能帮我解决这个问题吗?

谢谢!

1 个回答

1

谷歌云盘(当我打开drive.google.com时,我看到下面的文件夹结构)
myProject
ImageToDoc
images

听起来你是从自己的账户打开谷歌云盘网页应用。

不过你的代码显示你在使用一个服务账户。

credentials = service_account.Credentials.from_service_account_file(json_key_path)

你有没有把这个文件夹分享给你的服务账户?如果没有的话,它就没有权限访问,所以看不到这些文件。就像我如果搜索这个文件夹也找不到一样。

谷歌云盘和Colab

老实说,我不太明白你为什么要在Colab中使用服务账户。除非你真的想通过谷歌云盘的API来操作,这样的话你就准备好了。

其实你可以直接在Colab中挂载你的谷歌云盘账户。

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

撰写回答