如何将提取的数据保存到文本文件

how to save extracted data to a text file

我有一个包含以下内容的文本文件

this is the first line
this is the second line
this is the third line
this is the fourth line and contains the word fox.

目标是编写读取文件的代码,提取行 其中的单词 fox 并将该行保存到新文本 file.Here 是我目前的代码

import os
import re

my_absolute_path = os.path.abspath(os.path.dirname(__file__))

with open('textfile', 'r') as helloFile:

    for line in helloFile:

        if re.findall("fox",line):

            print(line.strip())

此代码打印已解析文本的结果,但这并不是我真正想要的。相反,我希望代码使用该行创建一个新的文本文件。在 python 中有没有办法做到这一点?

你可以这样做:

with open('textfile', 'r') as in_file, open('outfile', 'a') as out_file:
    for line in in_file:
        if 'fox' in line:
            out_file.write(line)

这里我打开了outfile in append (a)模式来适应多次写入。并且还使用了 in (str.__contains__) 检查子字符串是否存在(正则表达式在这里绝对是矫枉过正)。