blues.txt
aaaaaaaaaa
bbbbbbbbbb
探戈:55
dddddddddd
我想做到这一点
aaaaaaaaaa
bbbbbbbbbb
探戈:5500
dddddddddd
我的Python书没有有关如何执行此操作的信息。
f = open("blues.txt", 'r', encoding = 'utf')
jool = f.readlines()
find("tango")
line(find)
答案 0 :(得分:1)
您可以通过以下方法实现这一目标:
with open('blues.txt','r') as f:
with open('out.txt','w') as out:
for line in f:
if 'tango' in line:
out.write(line.replace('\n','00\n'))
else:
out.write(line)
输出:
aaaaaaaaaa
bbbbbbbbbb
tango:5500
dddddddddd
在各行中,如果该行包含单词“ tango”,则只需执行if语句即可处理所需的操作
编辑(如果您想要行号(从1开始),请执行以下操作:
count=1
with open('blues.txt','r') as f:
with open('out.txt','w') as out:
for line in f:
if 'tango' in line:
out.write(line.replace('\n','00\n'))
print('changed line '+str(count))
else:
out.write(line)
count+=1
输出:
changed line 3
答案 1 :(得分:1)
您需要做的就是在行中检测一个子字符串,然后添加00并使用.join:
f = open("blues.txt", "r", encoding = "utf")
lines = f.readlines()
for i in range(len(lines)):
if lines[i].find("tango") != -1:
lines[i]+="00"
f.close
f = open("blues.txt", "w", encoding = "utf")
f.write(lines.join("\n"))