我有一个文本文件,如下所示:
line1
1
2
line2
line3
1
2
line4
1
2
line5
line6
如果一行和下一行以字符串line
开头,则它应该
在行之间打印0
。
所以输出应该如下所示:
line1
1
2
line2
0
0
line3
1
2
line4
1
2
line5
0
0
line6
答案 0 :(得分:0)
如果我理解正确,文件如下:
line1
1
2
line2
line3
1
2
line4
...
如果您想添加两个新行' 0'你应该这样做:
with open("your_file.txt") as txt_file:
lines = txt_file.readlines()
prev_starts_with_line = False
for line in lines:
if line.find("line") == 0:
if prev_starts_with_line:
print "0\n0"
prev_starts_with_line = True
else:
prev_starts_with_line = False
print line.strip()
输出将是:
line1
1
2
line2
0
0
line3
1
2
line4