[英]How can I take user input and write it to a Text file?
This is my code:这是我的代码:
def student_info(name,age,gender):
print("The student name is:",name)
print("The student age is:",age)
print("The student gender is:",gender)
print("*"*70)
Student_name=input("Enter Student name:")
Student_age=input("Enter Student age:")
Student_gender=input("Enter Student gender:")
print("*"*70)
with open('Try1.txt', 'w') as f:
student_info(Student_name,Student_age,Student_gender)
f.write((Student_name,Student_age,Student_gender)
I try to write the user inputs into a text file but the code doesn't work.我尝试将用户输入写入文本文件,但代码不起作用。 I don't know why.
我不知道为什么。 Help, please.
请帮忙。
There are a couple of things wrong with your code.您的代码有一些问题。
You try to pass a tuple to write, write only takes a single str type argument so you need to change that.你尝试传递一个元组来写入,写入只需要一个 str 类型的参数,所以你需要改变它。
The f.write should be in the with statement. f.write 应该在 with 语句中。 student_info, on the other hand, should be outside the with statement.
另一方面,student_info 应该在 with 语句之外。
So your code should look something like this:所以你的代码应该是这样的:
with open('Try1.txt', 'w') as f:
f.write(Student_name+" "+Student_age+" "+Student_gender)
student_info(Student_name,Student_age,Student_gender)
Be aware, your programme overrides everything that is already in the file.请注意,您的程序会覆盖文件中已有的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.