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

1
  • 1
    Do you want to replace exact word or any substring? because r'samuel' will return True for asamuela as well. Commented May 10, 2013 at 15:48

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.