Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

python - How to append new data onto a new line

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

hs.write(name + "
")

This uses a backslash escape, , 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("{}
".format(name))

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...