Hello everyone

I recently thought about how to use python to find the text in a specific file
and write an additional file?

You can refer to the following example
and I have added annotations Description

 

import os

# file to read
files = [
     'TEST_1.TXT',
     'TEST_2.TXT',
     'TEST_3.TXT',
]

# The text need to find
keyWord = 'ABC'

getLines = []

# Loop to read the files
for fileF in files:
     with open(fileF, "r", encoding="utf-8") as f:
         for lineS in f. readlines():
             # Skip if the line does not have the text you are looking for
             if not keyWord in lineS:
                 continue
             # display found text lines
             print(lineS)
             # Gather the found text lines
             getLines.append(lineS)
            
# Sort the found lines, it is easier to read
getLines. sort()

# Write the found data lines, w+ is to write and add files
with open('summary.txt', 'w+') as f:
     for getLine in getLines:
         f. write(getLine)
         # It is better to write one more newline for better reading
         f.write('\n')

 

I hope it will be helpful to everyone.