如何在Python中为字符串添加换行符?

时间:2016-04-18 15:50:50

标签: python file

我正在将名称和分数添加到文件中,并试图找出在将数据写入文件后如何启动换行符。到目前为止,这是我的代码,但是当我继续执行该文件时,所有变量都在同一行:

print "That's the game folks! You finished with a final score of...", points, 'points! Good game, you made the high score list! What is your name?'
name = raw_input()
w = open('Highscores', 'a')
w.write(name)
w.write(str(points))
w.close()

3 个答案:

答案 0 :(得分:1)

对unix使用\n或Windows使用\r\n。只需添加到字符串的末尾。

w.write(str(points) + '\n')

print "That's the game folks! You finished with a final score of...", points, 'points! Good game, you made the high score list! What is your name?\n'

答案 1 :(得分:0)

执行以下操作,

print(name, points, sep=":", file="Highscores") # Mike:23 

你甚至不必做str(points)。适用于任何数据类型。并默认添加换行符。与使用.write()的自定义杂技相比,它非常高效。( Beazly

答案 2 :(得分:0)

这在Py3中变得更漂亮了:

print("That's the game folks! You scored %i points! Your name?" % points)
with open('Highscores', 'a') as w:
    print('%s %i' % (input(), points), file=w)

如果您只想为每个用户输入一个条目(即特定用户的最高分数且没有重复项),您可以使用字典并执行以下操作:

>>> from ast import literal_eval
>>> def save_score(name, score):
...     try:
...         d = literal_eval(open('score').read())
...     except:
...         d = {}
...     if name not in d or d[name] < score:
...         d[name] = score
...         open('score', 'w').write(str(d))
...
>>> save_score('Jack', 5)
>>> save_score('Jill', 10)
>>> open('score').read()
"{'Jill': 10, 'Jack': 5}"