首页 > 解决方案 > 如何从用户那里获取多个输入并将它们写入文件

问题描述

我必须将用户的姓名、年龄和身高作为输入,并使用这种格式将它们写入文件。姓名、年龄、身高。我可以使用单个输入,但无法弄清楚多个输入。这是我尝试过的。

name=input("enter name: ")
age=int(input("enter age"))
height=int(input("enter height"))
text_file = open('file_name', 'w')
text_file.write(name, '\n', age, '\n', height)
text_file.close()

但这给出了一个错误, write() 只接受一个参数。

标签: python-3.x

解决方案


啊,我自己弄的。错误出现在 write() 函数中。这是正确的说法:

text_file.write(str(name)+ str(age) +str(height))

或者

text_file.write(str(name)+ '\n'+ str(age)+ '\n' +str(height))

我用逗号代替了“+”。这就是错误的原因。

谢谢大家的意见。


推荐阅读