0

It appears that the best way to insert into the middle of a file in Python is via the manual process of copying the file, inserting into the copy, and then rewriting to the file. See Insert line at middle of file with Python? and Insert contents of a file in middle of another file with Python?. Is there a Python package that does all of this under the hood? Such a package might allow the user to specify the file, the position within the file, and the data to insert. If no package exists, what challenges would prevent such a package from being developed?

David Hansen
  • 501
  • 4
  • 14
  • It is impossible without a naive copy. Because a file are a set of blocks in the disk, how can you guarantee that the rest of content will not affected if such API is allowed? BTW, some File API, such as `RandomAccessFile` in Java is able to replace a record at any place when the length of a record is fixed. But anyway, inserting into the middle without copying is infeasible. – chenzhongpu Nov 23 '21 at 08:53
  • 1
    There is probably no such package, since this can essentially be done in 5 to 10 lines of code, as the answers to the linked questions show. – 9769953 Nov 23 '21 at 09:07
  • If something can be done with 5-10 lines of code it is generally better to code it on your own. If you want to keep your current code clean you can just write it in another file in the same directory and import whatever you need from there. Packages come with a lot of other stuff as well taking up install time and resources. – amalp12 Nov 23 '21 at 09:18
  • The Python `fileinput` library allows you to modify the files with `inplace=True`. For example, you could simply `for line in fileinput.input(..., inplace=True): print(line, eof='')` and then add another `print` when your conditions are true (line number == 123 or whatever). – tripleee Nov 23 '21 at 09:35

0 Answers0