Python find pattern and replace entire line

2019-07-04 04:33发布

问题:

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:

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)