如何将新数据附加到新行 [英] How to append new data onto a new line

查看:42
本文介绍了如何将新数据附加到新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

def storescores():

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

所以如果我运行它并输入Ryan"然后再次运行并输入Bob"文件 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 将其转换为字符串文字中的换行符.它只是将您的字符串 name 和该换行符连接成一个更大的字符串,然后写入文件.

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.

这篇关于如何将新数据附加到新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆