Append text to the last line of file with python

Question:

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.

enter image description here

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("worldn")
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.

enter image description here

Asked By: YunjieJi

||

Answers:

Is using echo with -n an option when you’re creating a.txt first time

echo -n ‘hello,’ >> a.txt

Otherwise read file first in a list ,use strip(n) with each element while reading and then rewrite the file before appending more text

Answered By: user5200389

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 file
    f.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
Answered By: PM 2Ring
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.