【问题标题】:Writing text (from a variable) into a file and on a new line in Python将文本(从变量)写入文件并在 Python 中的新行上
【发布时间】: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


【解决方案1】:

嘿,您所做的不是每次都写入要覆盖的文件的末尾 'w' 您需要做的是使用 'a' 将其附加到文件中

f = open('test.txt', 'a')

还要写一个新行,你必须通过声明一个新行“\n”来告诉程序你正在做什么

f.write(sumOfStudent + "\n")

【讨论】:

  • 啊,我看到上面的 cmets 已经解决了你的问题 :) 抱歉我迟到的答案。
猜你喜欢
  • 2015-02-27
  • 1970-01-01
  • 1970-01-01
  • 2014-02-26
  • 2015-09-18
  • 1970-01-01
  • 2023-01-25
  • 2013-06-30
  • 2012-06-04
相关资源
最近更新 更多