【问题标题】:Trying to find certain files using python and regex尝试使用 python 和正则表达式查找某些文件
【发布时间】:2021-11-24 16:15:47
【问题描述】:

所以我目前正在用 python 编写代码来查找某些文件,这是我当前项目的关键部分。我在 python 中使用 os 和 re 模块(现在)。当我这样做时,我得到两个结果。我当前的代码:

import os
import re

counter = 0
inp = input("What are you looking for?:> ")
thisdir = os.getcwd()
for r, d, f in os.walk("C:\\"):
    for file in f:
        filepath = os.path.join(r, file)
        filepathCheck = filepath
        if str(filepathCheck) is not re.search(r"((.+?).lnk)", str(filepath)):
            if inp in filepathCheck:
                counter += 1
                print(filepathCheck)

print("There are", counter, "files.")

我得到的结果是:

C:\Users\test\AppData\Roaming\Microsoft\Windows\Recent\Secrets.txt.lnk
C:\Users\test\Documents\Secrets.txt
There are 2 files.

我不想打印以 .lnk 结尾的文件,我只想要 Documents 中的文件。如果有人能够提供帮助,将不胜感激!

【问题讨论】:

  • 请您编辑您的问题以用文字描述代码 sn-p 的目的是什么?例如,如果它打算在某处搜索某种类型的文件,而忽略某些文件,或者其他什么。很难从代码中直观地看出它在逻辑上应该做什么,特别是如果代码实际上并没有按照它的意图去做。

标签: python string file-search


【解决方案1】:

您的if 声明是错误的。我不确定你认为str(filepathCheck) is not re.search(...) 中的is not 是做什么的。

您不需要使用正则表达式来查看文件路径是否以.lnk 结尾!只需改用str.endswith()docs

更改这些行:

if str(filepathCheck) is not re.search(r"((.+?).lnk)", str(filepath)):
    if inp in filepathCheck:

if not filepath.endswith(".lnk") and inp in filepath

filepath 已经是字符串了,不需要再转成字符串。还有filepathCheckfilepath是一样的,所以用同一个变量就行了

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    相关资源
    最近更新 更多