【问题标题】:no EOL after append to file in python在python中追加到文件后没有EOL
【发布时间】:2013-08-02 18:48:18
【问题描述】:

我尝试使用以下代码使用 python 附加到文件:

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

问题是当我用vim打开一个文件时,我在底部收到一条来自vim的消息:

"test.txt" [noeol] 2L, 27C

据我了解,这意味着该文件中没有 EOL。它发生在附加 python 之后。如果我用cat 打印文件,我会得到:

user@myubuntu:~/py_code$ cat test.txt
appended text
appended textuser@myubuntu:~/py_code$

当我用 vim 编辑 test.txt 并保存时,我从 cat 得到结果:

user@myubuntu:~/py_code$ cat test.txt
appended text
appended text
user@myubuntu:~/py_code$

注意“user@myubuntu:~/py_code$”现在应该在新行上。所以我得出结论,在附加 python 后 EOL 存在一些问题,但我不明白为什么以及如何解决这个问题。

【问题讨论】:

    标签: python file-io append eol


    【解决方案1】:

    将换行符 (\n) 附加到每一行。

    myfile.write("appended text\n")
    

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

    【讨论】:

    • 感谢您非常简单的回答。我在玩 '\n' 但没有得到预期的结果。现在你的建议奏效了!
    猜你喜欢
    • 2020-10-28
    • 1970-01-01
    • 2014-06-02
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 2016-12-03
    相关资源
    最近更新 更多