How to append new data onto a new line

后端 未结 9 1755
一整个雨季
一整个雨季 2020-12-02 16:41

My code looks like this:

def storescores():

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

so if I run it and enter \"Ry

9条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 17:12

    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.

提交回复
热议问题