搜索文本文件并将结果保存到另一个文本fi

2024-10-01 17:22:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还很陌生,对它的编程技能非常有限。我希望你能在这里帮我。在

我有一个很大的文本文件,我正在搜索一个特定的单词。每一行都需要存储到另一个txt文件中。在

我可以搜索文件并在控制台中打印结果,但不能打印到其他文件。我该怎么办?在

f = open("/tmp/LostShots/LostShots.txt", "r")

searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "Lost" in line: 
        for l in searchlines[i:i+3]: print l,
        print

f.close()

泰铢 一月


Tags: 文件intxtforclose技能编程line
2条回答

一般来说,要正确匹配单词,您需要正则表达式;一个简单的word in line检查也会匹配blablaLostblabla,我假设您不需要:

import re

with open("/tmp/LostShots/LostShots.txt", "r") as input_file, \ 
        open('results.txt', 'w') as output_file:

    output_file.writelines(line for line in input_file
                           if re.match(r'.*\bLost\b', line)

或者你可以用一个更冗长的词

^{pr2}$

另外,您应该使用os.path.join来创建路径;另外,对于以跨平台的方式处理临时文件,请参阅tempfile模块中的函数。在

使用with上下文管理器,不要使用readlines(),因为它会将文件的全部内容读入列表中。相反,逐行迭代file object并查看是否存在特定的单词;如果存在-则写入输出文件:

with open("/tmp/LostShots/LostShots.txt", "r") as input_file, \ 
     open('results.txt', 'w') as output_file:

    for line in input_file:
        if "Lost" in line:
            output_file.write(line) 

请注意,对于python<;2.7,with中不能有多个项:

^{pr2}$

相关问题 更多 >

    热门问题