Python- 每次将数据附加到打印时更新 txt 文件

Python- Update txt file every time data appended to print

目前我正在做我的第一个项目,它包含一个餐厅程序。 要以 waiter/tres 身份登录,请输入您的姓名并将其添加到 TXT 文件中。

我的问题是,当我打印 TXT 文件 以查看 登录 的用户时,代码中不会显示更新列表 如果不是原始列表。

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")

第二个ELIF是我写的看到保存的名字(用户)。 但正如我所说,打印 TXT 文件时没有 包括我在第一个 IF.

中添加的内容

这可能会有所帮助。

输出

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:

感谢建议和解决方案。 非常感谢。

在第一行你读了所有的名字,只是在那之后你添加了更多的名字,所以 f_n 变量没有得到更新。

将“列表”选项更改为此

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

这将确保您每次选择此选项时都能阅读更新后的列表