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
>Solution :
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
- read the existing file up to the point where you want to insert
- write that content into a new file
- write the content that you want to insert into the new file
- read the rest from the existing file
- write that rest into the new file
- delete the existing file
- rename the new file to the same name as the old file