Search code examples
pythonubuntunewlinecarriage-return

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


I have a server running ubuntu 14.04. I transferred my code files from my local computer to the server, but I can't run my program correctly because of this part of my code:

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()

when I run it, the output is :

some stuffsome stuffsome stuffsome stuffsome stuff 

I can't understand why because if I run it on my local computer the output is:

some stuff 
some stuff 
some stuff 
some stuff 
some stuff 

that's really weird, any ideas?


Solution

  • Your code works fine. The lines are terminated by a single \n (linefeed) character as used in Linux.

    Probably you are viewing the content of text.txt in a Windows program, e.g. notepad? The expected line ending will be \r\n (carriage return, linefeed), but since the \r is missing notepad displays it as a single line.

    You could check on your Ubuntu server. Log in to a terminal and enter:

    $ cat text.txt
    

    in which case you should see the contents as you expect.

    Also, the final line open('text.txt', 'a').close() does absolutely nothing at all.