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

如何在pathlib的glob方法中使用case_sensitive参数?

Path.glob方法常见问题解答

1. 参数列表中*的含义

这个*是Python的语法标记,作用是分隔位置参数与仅限关键字参数。它强制要求*之后的参数(这里是case_sensitive)必须以关键字参数的形式传入,不能用位置参数传递。举个例子,你不能写成somepath.glob('*.txt', False),必须写成somepath.glob('*.txt', case_sensitive=False)。

2. case_sensitive参数报错的解决方法

你遇到的TypeError是因为你的Python版本低于3.10——case_sensitive是Python 3.10才新增到Path.glob中的参数,低版本Python不支持这个参数。

解决思路分两种:

  • 升级Python版本:直接将Python升级到3.10或更高版本,之后就能正常使用somepath.glob('*.txt', case_sensitive=False)的写法。
  • 不升级版本的替代方案:手动实现大小写不敏感的文件匹配,比如遍历文件后过滤后缀:
    from pathlib import Path
    
    target_path = Path("./your_target_dir")
    # 遍历所有文件,筛选出后缀为txt(忽略大小写)的文件
    for file in target_path.glob("*"):
        if file.suffix.lower() == ".txt":
            print(file)
    
    或者结合fnmatch模块实现更灵活的匹配:
    from pathlib import Path
    import fnmatch
    
    target_path = Path("./your_target_dir")
    for file in target_path.iterdir():
        if fnmatch.fnmatch(file.name.lower(), "*.txt"):
            print(file)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 14:23:16