如何将新的数据添加到新的行 [英] How to append new data onto a new line
问题描述
我的code是这样的:
My code looks like this:
def storescores():
hs = open("hst.txt","a")
hs.write(name)
hs.close()
所以,如果我运行它,进入瑞恩
然后再次运行它并输入鲍勃
文件hst.txt看起来像
so if I run it and enter "Ryan" then run it again and enter "Bob" the file hst.txt looks like
RyanBob
而不是
Ryan
Bob
我该如何解决这个问题?
How do I fix this?
推荐答案
如果你想换行,你必须写一个明确的。通常的方法是这样的:
If you want a newline, you have to write one explicitly. The usual way is like this:
hs.write(name + "\n")
此使用反斜线, \\ n
,它的Python转换成字符串文本中一个换行符。它只是你的符连接字符串,名称
,并换行符到一个更大的字符串,它被写入文件。
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))
所有这一切都在输入和输出教程章解释说。
这篇关于如何将新的数据添加到新的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!