Поиск и замена строки в файле в Python

Я думаю, что-то вроде этого python-interpreter должно сделать это. По сути, он python-interpreter записывает содержимое в новый pythonic файл и заменяет старый файл file новым:

from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove

def replace(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    #Copy the file permissions from the old file to the new file
    copymode(file_path, abs_path)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

python

file

2022-10-27T08:46:23+00:00