如何在文本文件中搜索包含特定单词的行,然后使用 "found" 行创建一个新文件

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

我需要在一些数据(文本文件)中搜索包含特定单词的行,然后创建一个仅包含 'found' 行的新文本文件。

例如,如果原始文本文件(data.txt)中的数据是:

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

我要搜索关键字 'Child',新的文本文件 (output.txt) 将是:

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

到目前为止,这是我的代码,我真的不知道如何将找到的行写入新文件。

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

现在我们可以分解了lines = [line for line in file.read().split('\n') if search_word in line]

file.read() returns整个文件的字符串

.split('\n') 将字符串变成一个列表,在每个换行符处断开它('\n' 是一个换行符)

if search_word in line 所以它只添加带有单词

的行

'\n'.join(lines) 将选定的行重新组合在一起,然后使用 write

将其写入文件