You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Box Python SDK通过文件夹名称判断文件夹是否存在?

通过文件夹名称判断Box平台文件夹是否存在的Python实现方法

Box Python SDK本身没有直接提供按名称判断文件夹存在的方法,但可以通过两种方式实现需求:遍历父文件夹子项或使用搜索API。

方法1:遍历父文件夹子项匹配名称

适合父文件夹内容较少的场景,直接遍历子项筛选目标文件夹:

def folder_exists_by_name(parent_folder_id, folder_name):
    parent_folder = client.folder(folder_id=parent_folder_id).get()
    offset = 0
    limit = 100
    while True:
        items = parent_folder.get_items(limit=limit, offset=offset)
        if not items:
            break
        for item in items:
            if item.type == "folder" and item.name == folder_name:
                return True, item.id
        offset += limit
    return False, None

使用示例

# 替换为你的父文件夹ID和目标文件夹名称
exists, folder_id = folder_exists_by_name("123456", "目标文件夹")
if exists:
    print(f"文件夹存在,ID为 {folder_id}")
else:
    print("文件夹不存在")

方法2:使用搜索API精准查找

适合父文件夹内容较多的场景,通过搜索API缩小范围,效率更高:

def folder_exists_by_name_search(parent_folder_id, folder_name):
    search_results = client.search().query(
        folder_name,
        ancestor_ids=[parent_folder_id],
        type="folder"
    )
    for result in search_results:
        if result.name == folder_name:
            return True, result.id
    return False, None

关键参数说明

  • ancestor_ids:限定搜索范围在指定父文件夹及其子文件夹内(若仅需查找直接子文件夹,建议用方法1)
  • type="folder":确保只返回文件夹类型的结果,避免和同名文件混淆

注意事项

  • 同一父文件夹内的文件夹名称是唯一的,但文件夹和文件可以同名,因此代码中必须通过item.type == "folder"严格筛选类型
  • 确保你的Box客户端拥有目标父文件夹的读取权限,否则会返回权限错误
  • 若需处理跨子层级的同名文件夹,需额外添加逻辑判断目标文件夹的层级位置

内容的提问来源于stack exchange,提问作者That Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 08:40:28