[英]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:例如,如果原始文本文件 (data.txt) 中的数据是:
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',新的文本文件(output.txt)将是:
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]
现在我们可以分解lines = [line for line in file.read().split('\n') if search_word in line]
file.read()
returns a string of the whole file file.read()
返回整个文件的字符串
.split('\n')
turns the string into a list, breaking it at every newline ( '\n'
is a newline) .split('\n')
将字符串转换为列表,在每个换行符处打破它( '\n'
是换行符)
if search_word in line
so it only adds the lines with the words if search_word in line
所以它只添加带有单词的行
'\n'.join(lines)
puts the elected lines back together, then writes it to the file with write
'\n'.join(lines)
将选定的行重新组合在一起,然后使用write
将其写入文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.