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)"
Kalle Richter
  • 8,008
  • 26
  • 77
  • 177
a45628
  • 1
  • because write only takes one argument (just like the error says). you need to concatenate your `first_name second_name gender` together – WhatsThePoint Jul 10 '17 at 09:17
  • Possible duplicate of [Correct way to write line to file in Python](https://stackoverflow.com/questions/6159900/correct-way-to-write-line-to-file-in-python) – Mayur Vora Jul 10 '17 at 09:22

2 Answers2

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))
omri_saadon
  • 10,193
  • 7
  • 33
  • 58
  • 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. – KrTG Jul 10 '17 at 09:42
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)
Akshay Apte
  • 1,539
  • 9
  • 24