简体   繁体   中英

Python- Update txt file every time data appended to print

Currently I'm doing my first project which consists on a program for restaurants. To log in as a waiter/tres you insert your name and is added to a TXT file.

My problem is that in the code when I print the TXT file to see the users that signed in it won't show the updated list if not the original list.

snames = list()
f_n = (open('names.txt')).read()
print("Welcome to NAME.app")
try:
    while True:
        name = input("Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:")
        if name.lower() == "add":
            n_input = input("Name:")
            with open('names.txt', 'a') as f:
                f.write(n_input + '\n')
            continue

        elif name.lower() == "list":
            print(f_n.split())

        elif name == snames:
            print("Logged as", name)#doubtful line. print name of list.


        elif name == "exit":
            exit()
except:
    print("Invalid input")

In the second ELIF is what I wrote to see saved names(users). But as I said prints the TXT file without including what I added in the first IF .

This might help.

OUTPUT

Welcome to NAME.app
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:add
Name:Python
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:list
['Ale', 'Sarah', 'Annette', 'Dan']
Please select waiter/tress NAME - ADD to save new name - LIST to see saved names:

Appreciate recommendations and solutions. thank you very much.

In the first line you read all the names, only after that you added more names, so the f_n variable doesn't get updated.

Change the "list" option to this

elif name.lower() == "list":
    with open('names.txt') as f:
        print(f.read().splitlines())

This will make sure to read the updated list each time you choose this option

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM