Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python find pattern and replace entire line

Tags:

python

replace

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.

like image 582
Firze Avatar asked Nov 27 '25 02:11

Firze


1 Answers

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)
like image 52
Inbar Rose Avatar answered Nov 28 '25 16:11

Inbar Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!