I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory
fileinput is quite straightforward as mentioned on previous answers:
import fileinput
def replace_in_file(file_path, search_text, new_text):
with fileinput.input(file_path, inplace=True) as f:
for line in f:
new_line = line.replace(search_text, new_text)
print(new_line, end='')
Explanation:
fileinput
can accept multiple files, but I prefer to close each single file as soon as it is being processed. So placed single file_path
in with
statement.print
statement does not print anything when inplace=True
, because STDOUT
is being forwarded to the original file.end=''
in print
statement is to eliminate intermediate blank new lines.Can be used as follows:
file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')