0

How does one edit specific lines of a file?

Example

    What's your name?
    What do you do?
    What's your favourite colour?

And then after running a specific program, the outcome will be..

    What's your name? : Thatile
    What do you do? : I am a student
    What's your favourite colour? : Black

Using file.seek() overwrites and I want to keep the original text in the file, just edit lines

jpp
  • 159,742
  • 34
  • 281
  • 339
Thatile
  • 5
  • 3

2 Answers2

0

A simple solution (though not memory efficient) is to read the whole file to memory (using file.read() or file.readline() in a loop), edit the data you obtained to append the answers, then write the modified data to the original file (overwriting its original content).

Again, this is not memory efficient and could take a long time on a large file.

Aimery
  • 1,559
  • 1
  • 19
  • 24
0

Short answer: you cannot "edit a specific line in a file", you have to read the whole file and overwrite it with the edited content. The safe and memory-efficient way is to

  1. open a temporary file for writing
  2. open the original file for reading
  3. loop over the original file's content and for each line, update the line with your new content and write it to the temporary file
  4. close all files and replace the original with the temporary one
bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • Does Python write to the on-disk file when `write` is called, or only when `close` is called? If the latter (which I believe is the case), it won't really be memory efficient... – Aimery May 28 '18 at 12:13
  • @Aimery by default Python uses the OS/filesystem buffering - and yes it IS memory-efficient, as the system will flush the buffer to disk when it reaches a given size (and everything remaining when closing the file). Chances you come up with a better balance between memory use and IO latency by rewriting this manually are really really low... – bruno desthuilliers May 28 '18 at 12:21