-1

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

enter image description here

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
YunjieJi
  • 45
  • 2
  • 11
  • 2
    But you do not have to write a new line with echo. You can use `echo -n 'hello,'` to omit that. – Willem Van Onsem Feb 26 '17 at 13:41
  • 1
    Possible duplicate of [Prepend line to beginning of a file](http://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file) – hashcode55 Feb 26 '17 at 13:43
  • 2
    Please see [Why may I not upload images of code on SO when asking a question?](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a-question) – PM 2Ring Feb 26 '17 at 13:47
  • OMG! You gave me inspiration. Actually, I use `echo` to create a new line and then use `sed` to append another data at this line, and then use Python to append another data. So now, I can always use `echo -n` to append data in bash and finally use python to append another data, that's right?@WillemVanOnsem – YunjieJi Feb 26 '17 at 13:49
  • You can't append data before the end of the old file contents with a file opened in an append mode, you need `'r+'`. Please see http://stackoverflow.com/a/1466036/4014959 – PM 2Ring Feb 26 '17 at 13:50
  • 1
    please replace the pictures by text – miracle173 Feb 26 '17 at 13:59
  • 1
    Pretend that you have never heard of `echo`, and use `printf` instead. – chepner Feb 26 '17 at 14:21

2 Answers2

1

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
Community
  • 1
  • 1
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182
0

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