3
def replace(file_path, pattern, subst):
   file_path = os.path.abspath(file_path)
   #Create temp file
   fh, abs_path = mkstemp()
   new_file = open(abs_path,'w')
   old_file = open(file_path)
   for line in old_file:
       new_file.write(line.replace(pattern, subst))
   #close temp file
   new_file.close()
   close(fh)
   old_file.close()
   #Remove original file
   remove(file_path)
   #Move new file
   move(abs_path, file_path)

I have this function to replace string in a file. But I can't figure out a good way to replace the entire line where the pattern is found.

For example if I wanted to replace a line containining: "John worked hard all day" using pattern "John" and the replacement would be "Mike didn't work so hard".

With my current function I would have to write the entire line in pattern to replace the entire line.

1
  • Are you asking how to do it without changing this code? Because I would think if you can change this code the answer should be pretty straightforward. Commented Oct 21, 2013 at 13:17

1 Answer 1

7

Firstly, you could change this part:

for line in old_file:
    new_file.write(line.replace(pattern, subst))

Into this:

for line in old_file:
    if pattern in line:
        new_file.write(subst)
    else:
        new_file.write(line)

Or you could make it even prettier:

for line in old_file:
    new_file.write(subst if pattern in line else line)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.