简体   繁体   中英

How to search a text file for lines that contain a specific word, then create a new file with the "found" lines

I need to search some data (text file) for lines that contain a specific word, then create a new text file that only contains 'found' lines.

For example, if the data in the original text file (data.txt) was:

Child 9  60lbs  Female Diabetes
Adult 25 180lbs Male   ADHD
Adult 46 200lbs Female epilepsy
Child 10 65lbs  Female ADHD

And I was to search for the keyword 'Child', the new text file (output.txt) would be:

Child 9  60lbs  Female Diabetes
Child 10 65lbs  Female ADHD  

This is my code so far, I don't really know how to go about writing the found lines to a new file.

def main():
    
    Word1 = 'Child'
    
    #open an existing file. 
    OriginalData = open('recordData.txt', 'r')
    datalist = []

    for line in OriginalData.readlines():
            if Word1 in line: 
                #write the line to new file.
    
if __name__=="__main__":
    main()
search_word = 'your search word here'
with open('data.txt') as file:  # opens it, then closes it automatically at the end of the with block
    lines = [line for line in file.read().split('\n') if search_word in line]

with open('output.txt', 'w+') as output_file:  # 'w+' specifies it can be written to and created
    output_file.write('\n'.join(lines))

Now we can break down lines = [line for line in file.read().split('\n') if search_word in line]

file.read() returns a string of the whole file

.split('\n') turns the string into a list, breaking it at every newline ( '\n' is a newline)

if search_word in line so it only adds the lines with the words

'\n'.join(lines) puts the elected lines back together, then writes it to the file with write

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM