0

Here is my task: Write a sign up program for an after school club, it should ask the user for the following details and store them in a file: First Name, Last Name, Gender and Form.

Here is my code so far:

f= open("test.txt","w+")
first_name = input("Enter your First name>>>> ")
last_name = input("Enter your Last name>>>> ")
gender = input("Enter your gender>>>> ")

with open("test.txt", "a") as myfile:
    myfile.write(first_name, second_name, gender)

I have created the file but when I try to write to it I get an error saying

myfile.write(first_name, last_name, gender)
TypeError: write() takes exactly 1 argument (3 given)"
2
  • because write only takes one argument (just like the error says). you need to concatenate your first_name second_name gender together Commented Jul 10, 2017 at 9:17
  • Possible duplicate of Correct way to write line to file in Python Commented Jul 10, 2017 at 9:22

2 Answers 2

1

Following is the syntax for write() method −

fileObject.write( str )

This means you need to concat your arguments into one string.

For example:

myfile.write(first_name + second_name + gender)

Or you can use format as well:

fileObject.write('{} {} {}'.format(first_name, second_name, gender))
Sign up to request clarification or add additional context in comments.

1 Comment

It can also be done with myfile.write(' '.join((first_name, second_name, gender))) It's more useful if you just have a list of things without a particular meaning, like a list of numbers.
0

as the write function takes a single string argument, you have to append the strings into one and then write them to a file. You can't pass 3 different strings at once to myfile.write()

final_str = first_name + " " + second_name + " "+gender
with open("test.txt", "a") as myfile:
    myfile.write(final_str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.