0

Let's suppose I have a file, demo.txt. This file contains three lines which are:

 - line 1
 - line 2
 - line 3

I want to edit this file lines while iterating the demo.txt. For example, the program started to iterating, and now we are at line 1.

Now we modify this line to line 1.1 and press Enter the continue to iterate to the line 2. When I pressed enter the line 1.1 is saved to demo.txt file.

Then the same thing for line 2, i have changed line 2 to line 2.2 and pressed enter. The same thing for line 3: Change to line 3.3, press Enter to save and finished. This should be apply to every line. Is there a way to achieve that?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
xKralTr
  • 101
  • 9

2 Answers2

1

Like others explained in comments, you should not read a file while changing its content at the same time. You'll get either bad performance or inconsistent results (or both). You should either buffer the input for reading or buffer the output for writing.

Here is a solution that buffers the input file:

from pathlib import Path

def main():
  path = Path("demo.txt")
  lines = path.read_text().splitlines()

  with path.open("w") as f:
    for line in lines:
      new_line = transform(line)
      f.write(f"{line}\n")

if __name__ == "__main__":
  main()

Here, transform is a function that transform a line into a new line. the input file demo.txt is overwritten.

The other way around, i.e. buffering writes, would be:

from pathlib import Path

def main():
  path = Path("demo.txt")
  new_lines = []

  with path.open() as f:
    for line in f:
      new_line = transform(line)
      lines.append(f"{new_line}")

  path.write_text("\n".join(new_lines))

if __name__ == "__main__":
  main()

Alternatively, you can create a new file with a different name as suggested in another answer.

Louis Lac
  • 5,298
  • 1
  • 21
  • 36
0

As I mentioned in comments, we should not save in the same file once the line is processed which you are currently accessing/iterating over. Simply take the two files and open them one at a time and modify accordingly.

import os
with open('demo.txt') as file, open ('new.txt', 'w+') as file2:
    for line in file:
        s = input()
        if len(s) ==0:
            line = "modified\n"
            file2.write(line)

            print(line)

    file.close()
    file2.close()

os.replace('new.txt', 'demo.txt')

Your new demo.txt file looks like this

modified
modified
modified

What's happening here:

  1. Open your file and a temporary dummy file at once.
  2. Wait for user to hit enter. once he hits enter python reads line1 and saves to new line.
  3. once all the lines are finished, close the both files.
  4. Rename your temporary file with old original file name, i.e,, demo.txt
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131