简体   繁体   中英

Python find pattern and replace entire line

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM