gpt4 book ai didi

python - 插入带有文件特定值的换行符

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:42 28 4
gpt4 key购买 nike

我想在具有特定值的文件中搜索并给出换行符并写入现有文件和单独的文件

源代码

input_file= "test.txt"
putput_file="result.txt"
def search_break(input_file):
with open(input_file) as f:
lines = f.readlines()
print lines
for i in range(len(lines)):
if i == "Foo":
print
print lines[i]
if i== "50.000"
print
print lines[i]

f.close()



print search_break(input_file)

输入文件-test.txt

50.000
0.6016
1.0000
Foo
0.7318
1.0000

输出文件-test.txt

50.000
0.6016
1.0000

Foo
0.7318
1.0000

输出文件-result.txt

50.000
0.6016
1.0000

Foo
0.7318
1.0000

任何建议将不胜感激。谢谢。

最佳答案

readlines 保留换行符,因此您需要在测试之前将其删除,否则它永远不会匹配。我还将所有搜索词合并为一组,并简化了循环:

with open(input_file) as f:
for line in f:
if line.strip().lower() in {"foo", "50.000"}: # added .lower() and changed match strings to lowercase
print
print line, # added comma to prevent the automatic newline

使用多个 if..else 语句:

with open(input_file) as f:
for line in f:
if line.strip() == "Foo":
print
elif line.strip() == "50.000":
print
print line, # added comma to prevent the automatic newline

关于python - 插入带有文件特定值的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21639178/

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