0

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()
Celius Stingher
  • 17,835
  • 6
  • 23
  • 53

1 Answers1

1

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.

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
  • 1
    i made a mistake i meant to change last name with number, i have to input a phone number as well as a first name – rocklee336 Oct 06 '19 at 22:53
  • It doesnt really matter its all strings. – Paul Rooney Oct 06 '19 at 22:53
  • @rocklee336 I changed the second input to print `""Enter Phone number: ""`. – Paul Rooney Oct 06 '19 at 23:03
  • also one more thing if you dont mind. i need it to read back so far i have this but it doesnt work inputFile=open("phoneindex.txt",'r') text= inputfile.read print(text) inputFile.close() – rocklee336 Oct 06 '19 at 23:16
  • Are you saying you want to read back the values while still in the loop? Or after the loop? `text= inputfile.read` is certainly wrong. You are just associating a function to a variable. You need to call the function if you want it to return anything e.g. `text= inputfile.read()`. – Paul Rooney Oct 07 '19 at 01:00