gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:33:00 24 4
gpt4 key购买 nike

我对 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()

谢谢一月

最佳答案

使用上下文管理器,不要使用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 中包含多个项目:

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

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

关于python - 搜索文本文件并将结果保存到另一个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19114408/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com