2

I know how to use seek() to move where Python will read a file. Is there any way to do this when in append mode when editing a file? (I have tried using r+ and a+ for read and write, but r+ overwrites the character in the specified position and a+ still seems to insert text at the end of the file)

file1.py:

filetwo = open("file2.txt", "a")
filetwo.seek(13)
filetwo.write("5")
filetwo.close()

file2.txt:

1, 2, 3, 4, 6, 7, 8, 9, 10

1 Answers1

2

The concept of files does not have something like an "insert" in any file system I know (but one could probably design such a file system). To achieve an insert you have to

  1. read the existing file up to the point where you want to insert
  2. write that content into a new file
  3. write the content that you want to insert into the new file
  4. read the rest from the existing file
  5. write that rest into the new file
  6. delete the existing file
  7. rename the new file to the same name as the old file
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222