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.