在python中附加到文件后没有EOL [英] no EOL after append to file in python
问题描述
我尝试使用以下代码使用 python 附加到文件:
I try to append to file with python using this code:
with open("test.txt", "a") as myfile:
myfile.write("appended text")
问题是当我用vim打开一个文件时,我在底部收到来自vim的消息:
The problem is that when I open a file with vim, I get a message from vim at the bottom:
"test.txt" [noeol] 2L, 27C
据我所知,这意味着该文件中没有 EOL.它发生在附加 python 之后.如果我用 cat
打印文件,我得到:
As I understand that means there is no EOL in that file. And it happens after appending with python. If I print the file with cat
, I get:
user@myubuntu:~/py_code$ cat test.txt
appended text
appended textuser@myubuntu:~/py_code$
当我用 vim 编辑 test.txt 并保存时,之后我从 cat 得到结果:
When I edit test.txt with vim and save, afterwards I get results from cat:
user@myubuntu:~/py_code$ cat test.txt
appended text
appended text
user@myubuntu:~/py_code$
注意user@myubuntu:~/py_code$"现在应该在新行上.所以我得出结论,在附加 python 后 EOL 存在一些问题,但我不明白为什么以及如何解决这个问题.
Pay attention that "user@myubuntu:~/py_code$" now is on the new line as it should be. So I make conclusion there is some problem with EOL after appending with python, but I do not understand why and how to fix this.
推荐答案
在每一行追加换行符 (\n
).
Append newline (\n
) to each line.
myfile.write("appended text\n")
附注.EOL(行尾)是换行符.
PS. EOL (end-of-line) is newline.
这篇关于在python中附加到文件后没有EOL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!