First, I use echo 'hello,' >> a.txt
to create a new file with one line looks like that. And I know \n
is at the last of the line.
Then I get some data from python, for example "world", I wish to append "world" at the first line, so I use the python code below:
f = open('a.txt','a')
f.write("world\n")
f.flush()
f.close()
And, here is the result. I know the start point for python to write is at the next line, but I don't know how to fix it.
To overwrite the previous file contents you need to open it in 'r+'
mode, as explained in this table. And to be able to seek to arbitrary positions in the file you need to open it in binary mode. Here's a short demo.
qtest.py
with open('a.txt', 'rb+') as f:# Move pointer to the last char of the filef.seek(-1, 2)f.write(' world!\n'.encode())
test
$ echo 'hello,' >a.txt
$ hd a.txt
00000000 68 65 6c 6c 6f 2c 0a |hello,.|
00000007
$ ./qtest.py
$ hd a.txt
00000000 68 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a |hello, world!.|
0000000e