Home > Software design >  Can't get user input to append to a file
Can't get user input to append to a file

Time:05-15

So I'm trying to use the command file.write(newItem "\n") to append text to a file but I'm having a problem. So here is my code:

file=open("devices.txt","a")
while True:
    newItem = input('Enter device name:')

    if newItem == 'exit':
        break

print("All done!")
file.write(newItem   "\n")

The problem here is, since the file.write command is after the exit command, the only thing it's appending to the file is the word exit, which isn't what I want on there at all. I have tried putting it above the if statement but that completely messes it up so I'm not really sure what to do. I've tried looking it up but can't find anything similar to this specific situation.

CodePudding user response:

You'll need to close your file object and put the write inside while block

file=open("devices.txt","a")
while True:
    newItem = input('Enter device name:')

    if newItem == 'exit':
        break
    file.write(newItem   "\n")

file.close()
print("All done!")

Alternatively, you can use context manager without the need to call close()

with open("devices.txt","a") as file
    while True:
        newItem = input('Enter device name:')

        if newItem == 'exit':
            break
        file.write(newItem   "\n")

print("All done!")
  • Related