-2

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).

OmG
  • 18,337
  • 10
  • 57
  • 90
  • 1
    It's not possible to insert/delete in the middle of a file. You can overwrite part of a file, but if the replacement isn't the same length as the original line you won't get the correct result. – Barmar Oct 25 '19 at 15:41
  • can show some sample file, explain the problem and what's your goal? – rok Oct 25 '19 at 15:47
  • I agree that it is impossible to write something in the middle of a file, imagine how could you accomplish this? The file is written continuously on the disk, and you need to replace the middle. – Sraw Oct 25 '19 at 15:47
  • @Sraw although the `new_line` has the same length as the line? – OmG Oct 25 '19 at 15:48

1 Answers1

1

You can only do this if the replacement line is the same length as the original line. Then you can do it by opening the file in read-write mode and overwriting the line in the file.

new_line = 'some text'
with open(file_addr, 'r+') as f:
    while True:
        line = f.readline()
        if 'keyword' in line:
            f.seek(-len(line), 1)
            f.write(new_line)
            break
Barmar
  • 741,623
  • 53
  • 500
  • 612