[英]define a function to search for a specific word in a text file and print total lines
[英]How to search a text file for lines that contain a specific word, then create a new file with the "found" lines
我需要在一些数据(文本文件)中搜索包含特定单词的行,然后创建一个仅包含“找到”行的新文本文件。
例如,如果原始文本文件 (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()
返回整个文件的字符串
.split('\n')
将字符串转换为列表,在每个换行符处打破它( '\n'
是换行符)
if search_word in line
所以它只添加带有单词的行
'\n'.join(lines)
将选定的行重新组合在一起,然后使用write
将其写入文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.