Python - 写入新行

Python - Writing to a New Line

我查看了有关此主题的许多其他主题,但似乎找不到在文件末尾附加新行的正确代码。

这是我的代码:

Name=input('What is your name:')
Date=input('What is the date:')
Score=input('What was your high score:')

myFile=open('Scores.txt','a')
myFile.write("{},{},{}"+"\n".format(Name, Date, Score))
myFile.close()

然而,似乎在 Score.txt 文件中输出的唯一内容是 {},{},{}。 我的预期输出是,每次我 运行 这个程序,它都会将新数据输出到一个新行,而不会覆盖它上面的行。

它正在格式化 \n(新行)字符串,然后添加大括号。试试这个。

myFile.write( ("{},{},{}"+"\n").format(Name, Date, Score) )

只需使用括号:

myFile.write(("{},{},{}"+"\n").format(Name, Date, Score))

或者,也许更好:

myFile.write(("{},{},{}\n").format(Name, Date, Score))

然后 .format 将应用于整个字符串。

当你这样做时:

"{},{},{}"+"\n".format(Name, Date, Score)

Python 解释为:

"{},{},{}"+("\n".format(Name, Date, Score))

因为方法调用.format(...) has a tighter binding+ 运算符。意思是,它仅适用于字符串 "\n" 而不是组合字符串 "{},{},{}"+"\n".

此外,在字符串 "\n" 上调用 str.format 方法实际上是空操作:

>>> "\n".format(1, 2, 3)
'\n'
>>>

因此,写入文件的字符串只是 "{},{},{}"+"\n""{},{},{}\n"


要解决此问题,只需在格式字符串中包含换行符即可:

myFile.write("{},{},{}\n".format(Name, Date, Score))

"{},{},{}"+"\n".format(Name, Date, Score)

您正在调用字符串 "\n" 上的 format 方法。

尝试"{},{},{}\n".format(Name, Date, Score)

试试下面的代码:

Name=input('What is your name:')
Date=input('What is the date:')
Score=input('What was your high score:')

myFile=open('Scores.txt','a')
myFile.write("{0}\n{1}\n{2}\n".format(Name, Date, Score))
myFile.close()

查看此文档https://docs.python.org/3/library/string.html#format-examples 以查看格式示例。

你还忘记在每个值上使用“\n”。

此致,

您目前正在格式化 \n

要格式化整个字符串,您需要说明 \n 是字符串的一部分。

myFile.write(str("{},{},{}"+"\n").format(Name, Date, Score))