Reputation: 1
I need the program to record multiple names and numbers, and then after i put them in the user hits enter and it exits
while(True):
string1=input("Enter First Name: ")
string2=input("Enter Last Name: ")
outFile= open("names.txt", 'w')
firstname= string1
lastname= string2
outFile.write(string1.upper()+"\n"+string2.upper()+"\n")
outFile.close()
Upvotes: 0
Views: 155
Reputation: 21619
You need to append to the file. At present you overwrite the file on each iteration.
while(True):
string1=input("Enter First Name: ")
if string1 == '':
break
string2=input("Enter Phone number: ")
with open("names.txt", 'a') as outFile:
outFile.write(string1.upper()+"\n"+string2.upper()+"\n")
You could also move the file open to be outside the loop. This would hold the file open until you quit the program.
with open("names.txt", 'w') as outFile:
while(True):
string1=input("Enter First Name: ")
if string1 == '':
break
string2=input("Enter Phone number: ")
outFile.write(string1.upper()+"\n"+string2.upper()+"\n")
There is slightly different functionality between these two versions. The first will preserve any content already in the file before the program runs. The later will overwrite any existing content and start the file afresh.
For more on with
and why it means you don't need to close the file yourself, see here.
Upvotes: 1