0

A file 'webiste.txt' contains text:

welcome to geeksforgeeks

Python code:

f  =  open('website.txt', 'a')
f.seek(11)
f.write("Python")
f.close()

desired out: welcome to python geeksforgeeks

real output: welcome to geeksforgeekspython

when I am running this code in 'a' mode the data gets appended at the last position not at 11th position. In 'w' mode the data gets entered at position 11th but rest of the data overwritten.

How can we add python at 11th index without overwriting?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Aman
  • 17
  • 5
  • ```open('website.txt','a+')``` Open file in ```a+```? –  Aug 02 '21 at 10:45
  • I think this may help you https://stackoverflow.com/questions/43567948/seek-function-doesnt-work-to-update-a-file-in-a-specific-position-python – Himanshu Singh Chauhan Aug 02 '21 at 10:50
  • 1
    what you are expecting is that when you will write at 11 pos, other text from 11 to end will shift automatically, I don't think there is a method for this. – Epsi95 Aug 02 '21 at 10:54
  • 1
    Does this answer your question? [Insert line at middle of file with Python?](https://stackoverflow.com/questions/10507230/insert-line-at-middle-of-file-with-python) – Tomerikoo Aug 02 '21 at 10:59
  • @Tomerikoo the answer you suggest not working. inserting python where I want to append – Aman Aug 02 '21 at 11:05
  • You only have one one line. Read it, change it, write it back... – Tomerikoo Aug 02 '21 at 11:10

1 Answers1

0

First open with 'r' method to read content and then use 'w' to rewrite the content and the following code may help :)

with open('website.txt','r') as f:
    content = f.read()
with open('website.txt','w') as f:   
    f.write(content[:11] + "Python" + content[11:])
Tranbi
  • 11,407
  • 6
  • 16
  • 33