如何使用python在文件中进行搜索和替换

时间:2013-05-10 15:39:56

标签: python

我在names.txt中有这样的文本文件:

My name is alex
My name is samuel

我想用拳击手取代塞缪尔

我的代码是:

#!/usr/bin/python

import re

f = open("names.txt",'r+')
for line in f:
  if re.search(r'samuel',line,re.I):
     print line
     m=f.write(line.replace("samuel",'boxer'))
f.close()

即使打印行正确打印了行,但在names.txt中没有进行替换。如果有人有任何线索,请告诉我

1 个答案:

答案 0 :(得分:3)

在这里使用正则表达式是过度的。 .replace()如果根本不存在替换文本,则返回行不变,因此无需进行均匀测试。

要替换文件中的数据,就可以更轻松地使用fileinput module

import fileinput

for line in fileinput.input('names.txt', inplace=True):
    line = line.replace('samuel', 'boxer')
    print line.strip()