2017-02-26 61 views
-1

首先的最后一行,我使用echo 'hello,' >> a.txt创建一个新的文件,一行看起来像这样。我知道\n是最后一行。附加文本文件与Python

enter image description here

然后我从蟒蛇的一些数据,例如“世界”,我想追加“世界”在第一线,所以我用下面的Python代码: f = open('a.txt','a') f.write("world\n") f.flush() f.close() 而且,这里是结果。我知道python的起点是在下一行,但我不知道如何解决它。

enter image description here

+2

但是你没有写回声一个新的生产线。你可以使用'echo -n'hello'来省略。 –

+1

[前面加上行到文件的开头](http://stackoverflow.com/questions/5914627/prepend-line-to-beginning-of-a-file)的可能的复制 – hashcode55

+2

请参见[为什么我可以不上传图片就问一个问题,所以当代码?](http://meta.stackoverflow.com/questions/285551/why-may-i-not-upload-images-of-code-on-so-when-asking-a - 问题) –

回答

0

是使用回声,当你创建A.TXT首次

回声-n '你好,' >> A.TXT

否则读文件-n选项首先在列表中,在读取每个元素时使用strip(\ n),然后在添加更多文本之前重写该文件

0

要覆盖以前的文件内容,需要在'r+'模式下打开它,如this table。为了能够在文件中寻找任意位置,您需要以二进制模式打开它。这是一个简短的演示。

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()) 

测试

$ 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