문제

I try to append to file with python using this code:

with open("test.txt", "a") as myfile:
    myfile.write("appended text")

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

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$

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$

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.

도움이 되었습니까?

해결책

Append newline (\n) to each line.

myfile.write("appended text\n")

PS. EOL (end-of-line) is newline.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top