【发布时间】:2014-12-10 16:31:49
【问题描述】:
def function(score,name):
sumOfStudent = (name + ' scored ' + str(score))
f = open('test.txt', 'wb')
f.write(sumOfStudent)
f.close()
user_name = input("Please enter yout full name: ")
user_score = int(input("Please enter your score: "))
function(user_score,user_name)
f = open('test.txt')
print(f.read())
f.close()
我正在用 python 编写一个简单的程序,它允许用户输入信息,然后将该文本存储在 .txt 文件中。这可行,但是它总是会写入同一行,我想知道如何每次都将f.write(sumOfStudent) 放在新行上(sumOfStudent 是保存用户输入的变量)谢谢!
【问题讨论】:
-
以换行符结束。
f.write(sumOfStudent + "\n") -
您以
'w'(overwrite)模式打开文件,而不是'a'(a追加)。跨度> -
@AdamSmith 感谢您的帮助!不敢相信就这么简单。
-
@jonrsharpe 也谢谢你,不知道为什么我使用'wb'模式!
标签: python python-3.x