seek() method In Python,
seek() function is used to change the
position of the File Handle to a given specific position. File handle
is like a cursor, which defines from where the data has to be read or
written in the file.
Please visit GFG site for more information regarding seek method.
When I tried to move the cursor to the end of the text file I got exception UnsupportedOperation: can't do nonzero end-relative seeks
so I have to seek only from the beggining of file.
text files do not have a 1-to-1 correspondence between encoded bytes
and the characters they represent, so seek can't tell where to jump to
in the file to move by a certain number of characters.
above quote from this site of stack overflow.
This might not be complete solution but it works and hope it might give you some help so you could use it to solve the problem.
os.stat
is used to get the file size. After knowing to file size we can use seek
method to go to appropriate position can modify the file efficiently.
import sys,random, os
file_convt = open("test.txt", "w")
for i in range(0, 3):
file_convt.write(str(i+1) + "\n")
file_convt.close()
stats = os.stat('test.txt')
#print(stats.st_size)
with open("test.txt", "r+")as f:
f.seek(stats.st_size-1,0) #now our cursor is after 3 and here we can write hello
f.write("hello\n")
Output:
$ cat test.txt
1
2
3hello