查找包含文本文件的文件夹中是否存在字符串

2024-03-28 23:07:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个密码

for i in list:
    if not not_existing_signals(i):
         #store the signal

def not_existing_signals(name_of_signal):
    for filename in Path('c:\....').glob('**/*.txt') :  
        with open(filename) as f:
            if name_of_signal in f.read():
                return True
    return False

我要做的是检查我的列表中的一个元素是否不存在于文件夹中的任何地方,如果它至少存在于一个文件中,我就不需要将它存储在任何地方。你知道吗

更新

所以我想要的是在文件夹中搜索一个signal name,而不是在每个文件中分别搜索,看看它是否不存在

我有大约100个信号名。例如,如果其中一个在第三个文件中,程序将返回false,因为它将检查它是否在第一个和第二个文件中。如果三个文件上没有信号,我想返回false


Tags: 文件ofnamein文件夹forsignalreturn
2条回答

你应该使用Regex。 试试这个:

import re
search = ((re.findall(name_of_signal,f.read(), re.IGNORECASE)))

上面我放在一起的可能不起作用,但是使用regex可能是实现您想要做的事情的最有效的方法。你知道吗

您试图构建的函数检查一个单词(即name_of_signal)是否不在目录
中的任何文件中 这意味着,如果至少有一个文件包含name_of_signal,则返回False;如果所有文件都不包含name_of_signal,则返回True。你知道吗

这可以被概念化为:

For each file in my folder, open the file and check if it contains the word name_of_signal. If the word is in the file, you can stop the iteration and return False (since the requirement is at least one file). If the word is not in the file, continue with the next file

您的函数是正确的,但它检查的结果正好相反:不是检查任何文件中是否包含单词,而是检查是否至少在文件中包含单词:

def not_existing_signals(name_of_signal):               # FUNCTION DEFINITION
    for filename in Path('c:\....').glob('**/*.txt') :  # for each file in folder
        with open(filename) as f:                       # open the file
            if name_of_signal in f.read():              # if name_of_signal is in the file
                return True                             # stop the iteration and return True
    return False                                        # if we've looked inside all the files and didn't found name_of_signal, return False

解决方案:

解决方法是将return Truereturn False交换:

def not_existing_signals(name_of_signal):               # FUNCTION DEFINITION
    for filename in Path('c:\....').glob('**/*.txt') :  # for each file in folder
        with open(filename) as f:                       # open the file
            if name_of_signal in f.read():              # if name_of_signal is in the file
                return False                            # stop the iteration and return False (MEANS: found at least one file with name_of_signal
    return True                                         # if we've looked inside all the files and didn't found name_of_signal, return True (MEANS: name_of_signals is not in the files!)

如果不想更改代码,只需更改函数名即可:

not_existing_signalsexisting_signals!!你知道吗

相关问题 更多 >