Вопрос

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