我想要搜索' banana' word并替换文件中的行
例如
的test.txt
"测试测试苹果tt estsetse setse tse banana tes test setset orange sets et setset 设置etst"
搜索' banana'并改变行
'设置香蕉测试' - >我喜欢香蕉'
答案 0 :(得分:1)
这很简单......
请考虑此代码......
fp = open('D://source.txt',"r+")
fg = open('D://target.txt',"w")
for line in fp:
if line.find("banana") != -1:
new_line = line.replace(line,"i like banana\n")
fg.write(new_line)
else:
fg.write(line)
fg.close()
fp.close()
答案 1 :(得分:1)
您也可以使用此示例:
lookup = 'banana'
with open(text.txt) as myFile:
for num, line in enumerate(myFile, 1):
if lookup in line:
# do some work
break # if the work is finished
elif not lookup in line:
# do smtg else
pass
myFile.close()