使用Python与regex搜索指定文件时如何排除.lnk后缀的快捷方式文件
代码修改方案
你原有代码的过滤逻辑存在错误,导致.lnk快捷方式没有被排除,修改后的完整代码如下:
import os counter = 0 inp = input("What are you looking for?:> ") for r, d, f in os.walk("C:\\"): for file in f: # 先过滤所有.lnk后缀的快捷方式文件 if file.endswith('.lnk'): continue filepath = os.path.join(r, file) if inp in filepath: counter += 1 print(filepath) print("There are", counter, "files.")
核心修改说明
- 删除了无效的正则匹配逻辑:原有代码中
str(filepathCheck) is not re.search(r"((.+?).lnk)", str(filepath))的判断逻辑完全不成立,re.search返回的是匹配对象或空值,和字符串做身份判断永远返回True,过滤规则完全没有生效 - 新增快捷方式过滤逻辑:在遍历文件时先判断文件名是否以
.lnk结尾,符合条件直接跳过当前文件,不会进入后续匹配逻辑 - 简化了冗余变量:删除了没有实际作用的
filepathCheck、thisdir变量、未使用的re模块导入,代码更简洁
如果你仍需要使用正则实现过滤,也可以将过滤逻辑替换为:
if re.search(r'\.lnk$', file): continue
效果和endswith判断完全一致。
内容的提问来源于stack exchange,提问作者Jaw_dropper
相关产品推荐
相关产品推荐

