Mohammed Meaad
Mohammed Meaad

Reputation: 9

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.

Upvotes: 1

Views: 57

Answers (1)

Tobias
Tobias

Reputation: 947

There are a couple of things wrong with your code.

  1. You try to pass a tuple to write, write only takes a single str type argument so you need to change that.

  2. The f.write should be in the with statement. student_info, on the other hand, should be outside the with statement.

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.

Upvotes: 1

Related Questions