Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't get user input to append to a file

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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!")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading