Alice
Alice

Reputation: 7

Basic file handling in python

i have been asked to create a program for an after school club, which should be stored in a file. I am new to python and my program says that "lines" is not defined. Please help!

##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

print ("Sign up for an after school club here")

firstname = input ("What is your first name?")
lastname = input ("What is your last name?")
gender = input("What is your gender?")
form = input("What is your form?")

f = open("afterschoolclub.txt","w")
lines = f.readlines()
print( lines[0])
f.write("\n",firstname)
f.write("\n",lastname)
f.write("\n",gender)
f.write("\n",form)
f.close()`

THIS PROGRAM IS NOW SOLVED

Upvotes: 1

Views: 299

Answers (1)

LetzerWille
LetzerWille

Reputation: 5658

You a trying to read still possibly empty file that you have open for writing....

use with open( that will close the file automatically for you .

with open("afterschoolclub.txt","w")     as f:

    f.write(firstname)
    f.write(lastname)
    f.write(gender)
    f.write(form)


with open("afterschoolclub.txt","r")     as f:
    lines = f.readlines()
    print( lines[0])

Upvotes: 1

Related Questions