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
toEPA150.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 theos.listdir()
method to get a list of filenames. You can read the file names usinglistdir("C:/Temp/lamip")
.Also, your
if
statement is wrong, you should do this instead:Here's the code:
PS: You can use
/
instead of\\
in your paths, Python automatically converts them for you.