【发布时间】:2018-07-02 13:26:23
【问题描述】:
我试图在匹配 'find me' 之前写一个新行,但我的代码将一个空行写入输出文件。我怎样才能摆脱那个空行(41.4 克之后的行)?
with open("input.txt", "r") as infile:
readcontent = infile.readlines()
with open("output.txt", "w") as out_file:
for line in readcontent:
if line.strip() == 'find me':
out_file.write('Added New line')
out_file.write(line)
输入.txt:
[atom]
molecules
41.4 gram
find me
2.1 kcal
completed
获得 output.txt:
[atom]
molecules
41.4 gram
Added New line
find me
2.1 kcal
completed
所需的输出.txt:
[atom]
molecules
41.4 gram
Added New line
find me
2.1 kcal
completed
【问题讨论】:
-
“找到我”之前总是有一个空行,“找到我”后面总是有一个空行吗?您想删除所有空行,还是只删除“找到我”之前的那些(并用不同的文本替换那些)?
-
“找到我”之前只有一个空行。我只想去掉那个空行。
-
如果那是唯一的空行,不要去寻找“找到我”,然后尝试摆脱之前的空行:相反,只需寻找空行本身。跨度>
标签: python