How to append new data onto a new line

RyanH2796 picture RyanH2796 · Feb 17, 2014 · Viewed 212.6k times · Source

My code looks like this:

def storescores():

   hs = open("hst.txt","a")
   hs.write(name)
   hs.close() 

so if I run it and enter "Ryan" then run it again and enter "Bob" the file hst.txt looks like

RyanBob 

instead of

Ryan
Bob

How do I fix this?

Answer

abarnert picture abarnert · Feb 17, 2014

If you want a newline, you have to write one explicitly. The usual way is like this:

hs.write(name + "\n")

This uses a backslash escape, \n, which Python converts to a newline character in string literals. It just concatenates your string, name, and that newline character into a bigger string, which gets written to the file.

It's also possible to use a multi-line string literal instead, which looks like this:

"""
"""

Or, you may want to use string formatting instead of concatenation:

hs.write("{}\n".format(name))

All of this is explained in the Input and Output chapter in the tutorial.