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

使用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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 09:24:05