0

I have a text file like this in names.txt:

My name is alex
My name is samuel

I want to just replace samuel with boxer

My code is :

#!/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()

even though Print line is printing the line correctly but replacement is not happening in names.txt. Let me know if anybody has any clue

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Tkills
  • 61
  • 1
  • 6

1 Answers1

3

Using a regular expression here is overkill. .replace() returns the line unchanged if the replacement text is not present at all, so there is no need to test even.

To replace data in a file, in place, it is easier to use the fileinput module:

import fileinput

for line in fileinput.input('names.txt', inplace=True):
    line = line.replace('samuel', 'boxer')
    print line.strip()
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343