Hackers45 Hackers45 - 5 months ago 33
Python Question

Python challenge 25: Writing files

Python Challenge 25

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

  • Form

For the above task I wrote the following python code:

# Python Challenge 25

print ("Hello user, this is a virtual application form"
"\nfor joining after-school clubs at -Insert school name here-")

first_name = input("\n\nPlease input your first name:")
last_name = input("Please input your last name:")
gender = input("Please input your gender:")
form = input("Please input your form name:")
club = input("What after-school club would you like to attend?\n")

file = open("application-form.txt", "w")
file.write (last_name)
file.write (gender)
file.write (form)
file.write (club)

print (first_name, "Thank you for taking your time to fill this virtual form"
"\nall the information has been stored in a file to maintain confidentiality")

An example of the outcome of the above code:

enter image description here

My question

  1. When the text file is saved all the user inputs is stored in one line, is there a way where I can put each input on a separate line?

  2. Is there a more efficient way to write the above code?

bli bli

Contrary to print, write doesn't automatically append end of lines. You can add file.write("\n") between your writes to intercalate ends of line.

Alternatively, you can create a single string interspersing the end of lines, using join, and write that single string.


file.write("\n".join([line1, line2, line3]))