I have a file and wanna replace a specific line that I can find it with search in file. I do that likes the following from this post:
import fileinput
new_line = 'some text'
with fileinput.FileInput(file_addr, inplace=True) as file:
for line in file:
if 'keyword' in line:
line = new_line
# Here #
print(line)
Now I want to terminate the loop in # Here #
. In this point, I found the line and replace it.
But if I break
the loop, the rest of the file will not be written into the file and will be removed. I am looking for a method just replace line when finding it and then terminate the loop.
The reason is the length of the file could be high and I don't wanna loop over the rest of the file.
Also, if there is a solution for the both case that the length of new_line
is the same as the length of the line or not (if it is matter).