在多个文本文件中搜索两个字符串?

sly*_*lam 4 python python-2.x python-2.7

我有一个包含许多文本文件的文件夹(EPA10.txt、EPA55.txt、EPA120.txt...、EPA150.txt)。我有 2 个要在每个文件中搜索的字符串,搜索结果写入文本文件 result.txt。到目前为止,我已经将它用于单个文件。这是工作代码:

if 'LZY_201_335_R10A01' and 'LZY_201_186_R5U01' in open('C:\\Temp\\lamip\\EPA150.txt').read():
    with open("C:\\Temp\\lamip\\result.txt", "w") as f:
        f.write('Current MW in node is EPA150')
else:
    with open("C:\\Temp\\lamip\\result.txt", "w") as f:
        f.write('NOT EPA150')
Run Code Online (Sandbox Code Playgroud)

现在我希望对文件夹中的所有文本文件重复此操作。请帮忙。

Mar*_*lli 7

鉴于您有一些名为EPA1.txtto的文件EPA150.txt,但您不知道所有名称,您可以将它们一起放在一个文件夹中,然后使用该os.listdir()方法读取该文件夹中的所有文件以获取文件名列表。您可以使用listdir("C:/Temp/lamip").

另外,你的if陈述是错误的,你应该这样做:

text = file.read()
if "string1" in text and "string2" in text
Run Code Online (Sandbox Code Playgroud)

这是代码:

from os import listdir

with open("C:/Temp/lamip/result.txt", "w") as f:
    for filename in listdir("C:/Temp/lamip"):
        with open('C:/Temp/lamip/' + filename) as currentFile:
            text = currentFile.read()
            if ('LZY_201_335_R10A01' in text) and ('LZY_201_186_R5U01' in text):
                f.write('Current MW in node is ' + filename[:-4] + '\n')
            else:
                f.write('NOT ' + filename[:-4] + '\n')
Run Code Online (Sandbox Code Playgroud)

PS:您可以在路径中使用/代替\\,Python 会自动为您转换它们。