Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you move the cursor while appending a file?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

  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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading