无法在 Ubuntu 服务器上使用 python 运行 在 .txt 中获取新行

Unable to get new line in a .txt with python running on Ubuntu server

我有一台服务器 运行ning ubuntu 14.04。我将我的代码文件从我的本地计算机传输到服务器,但由于我的这部分代码,我无法 运行 我的程序正确:

for _ in range(5):
    some = "some"
    stuff = "stuff"
    list_1 = open('text.txt', 'a')
    list_1.write("%s %s \n" %(some, stuff))
    open('text.txt', 'a').close()

当我运行它时,输出是:

some stuffsome stuffsome stuffsome stuffsome stuff 

我不明白为什么,因为如果我 运行 它在我的本地计算机上输出是:

some stuff 
some stuff 
some stuff 
some stuff 
some stuff 

这真的很奇怪,有什么想法吗?

您的代码运行良好。这些行由 Linux.

中使用的单个 \n(换行符)字符终止

您可能正在 Windows 程序中查看 text.txt 的内容,例如记事本?预期的行结尾将是 \r\n(回车 return,换行),但由于缺少 \r,记事本将其显示为单行。

您可以检查您的 Ubuntu 服务器。登录终端并输入:

$ cat text.txt

在这种情况下,您应该会看到您期望的内容。

此外,最后一行 open('text.txt', 'a').close() 完全没有任何作用。