我想在具有特定值的文件中搜索并给出换行符并写入现有文件和单独的文件
源代码
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
任何建议都会非常感激。谢谢。
答案 0 :(得分:1)
readlines
保留换行符,因此您需要在测试之前将其删除,否则它将永远不会匹配。我还将所有搜索词组合成一个set
,并简化了循环:
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