Python – Searching multiple text files for two strings

pythonpython-2.7python-2.x

I have a folder with many text files (EPA10.txt, EPA55.txt, EPA120.txt…, EPA150.txt). I have 2 strings that are to be searched in each file and the result of the search is written in a text file result.txt. So far I have it working for a single file. Here is the working code:

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')

Now I want this to be repeated for all the text files in the folder. Please help.

Best Answer

Given that you have some amount of files named from EPA1.txt to EPA150.txt, but you don't know all the names, you can put them altogether inside a folder, then read all the files in that folder using the os.listdir() method to get a list of filenames. You can read the file names using listdir("C:/Temp/lamip").

Also, your if statement is wrong, you should do this instead:

text = file.read()
if "string1" in text and "string2" in text

Here's the code:

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')

PS: You can use / instead of \\ in your paths, Python automatically converts them for you.

Related Topic