在python中追加到文件后没有EOL [英] no EOL after append to file in python

查看:78
本文介绍了在python中追加到文件后没有EOL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用以下代码使用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")

PS.EOL(行尾)是换行符.

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

这篇关于在python中追加到文件后没有EOL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆