Home > Enterprise >  Adding text to existing txt file using repeated user input
Adding text to existing txt file using repeated user input

Time:10-26

I want to let the user add numbers to the already existing phone list. The program should stop asking for input when the user only answers with enter. Here is what i've got so far ( I don't know why it doen't work as intended):

nums = open('telephone.txt', 'a')
print('Add name and number, finish with <enter>.')

while True:
    new = input('Name and number: ')
    nums.write('\n'   new)
    if new == '':
        break
nums.close() 

nums = open('telephone.txt', 'r')
print(nums.read())

edits: made suggested changes wo result

CodePudding user response:

You have everything required, though redefining new within the while loop is causing the reference to the file to be overwritten.

new = open('telephone.txt', 'a')

print('Add name and number, finish with <enter>.')
while True:
    userInput = input('Name and number: ')
    if userInput == '': break # If no input provided, stop listening for new numbers.
    
    new.write('\n'   userInput)

print(new.read())
new.close()

CodePudding user response:

python is making the variable new a file pointer on line one, and then making it a string on line 5, change the variable name of the user input

EX:

new = open('telephone.txt', 'a')
print('Add name and number, finish with <enter>.')

while True:
    usr_input = input('Name and number: ')
    new.write('\n'   usr_input)
    if usr_input == '':
        break
new.close()
  • Related