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

如何用Python列表推导式排序筛选文件名?解决PosixPath不可迭代报错

问题解决:PosixPath对象不可迭代的筛选错误

报错原因是你在筛选条件里直接用了"search words" in path,这里的path是Path模块返回的PosixPath对象,并非字符串类型,无法直接用in操作符判断子串是否存在。

以下是两种修正方案:

方案1:匹配完整路径中的关键词

将PosixPath对象转为字符串后再判断,会匹配路径(包括目录部分)中的关键词:

[path for path in sorted(Path(DIR_PATH).iterdir(), key=os.path.getmtime) if "search words" in str(path)]

方案2:仅匹配文件名中的关键词(更常用)

通过path.name获取文件/文件夹的名称字符串,只在文件名范围内搜索关键词:

[path for path in sorted(Path(DIR_PATH).iterdir(), key=os.path.getmtime) if "search words" in path.name]

额外扩展:仅筛选文件(排除文件夹)

如果需要只保留文件,可添加path.is_file()判断:

[path for path in sorted(Path(DIR_PATH).iterdir(), key=os.path.getmtime) if path.is_file() and "search words" in path.name]

内容的提问来源于stack exchange,提问作者Droid-Bird

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 15:25:15