[Solved] How to modify specific line in file [closed]


In general you don’t want to modify the contents of files directly (in-place) unless the data is formatted in fixed structures. The most common approach would be to rename the existing file, opening it to read, and opening a new file by the same name for write access. Then stream through the input data, performing any transformations or modifications before writing the data back out.

Another, safer, approach is to read from the existing file, write to a new file and perform a “link dance” to atomically link the new file into place under the old name while saving off the original to a backup name. (The phrase “link dance” is relevant to Unix and Linux filesystems … or others that offer similar semantics).

If you try to modify the file in place then you may find that you have to shift all of the data past various points where you’ve written changes in order to account for changes in data size. For example if any of those numbers in your data go from 3 digits to 4 or from 1 to any other size. You can do this … but it’s accompanied by a fairly high risk of data loss and corruption. This can be mitigated a little with some signal handling (blocking signals) and by using the mmap module to map the file into a region of memory and perform your operations using slicing/range primitives that translate well from Python into the lower level system operations that you’re performing on the data. That will be inherently more efficient than moving data in and out of buffers through read() and write() operations if your operating system support sane memory mapping semantics.

solved How to modify specific line in file [closed]