【问题标题】:Why does my code output the same dict pairs onto a text file?为什么我的代码将相同的字典对输出到文本文件中?
【发布时间】:2021-05-26 09:38:54
【问题描述】:

(Python 3.9)

所以我做了一个简单的程序,将用户名和密码记录在字典中(是的,我知道将密码存储为明文总是一个坏主意,但我正在学习字典和写入文件,而不是数据库和加密)并打印它们到文本文件中。

但这就是问题所在。 我输入用户名和密码。 它被保存到 dict 中。 for 循环 然后将每个 k, v 写入我的 with 语句中的文本文件,我的 dict 被打印到终端上,显示 k,v我刚才输入的确实在字典里。

我再次执行此过程,我的新组 k, v's 与之前的第一对再次存储在我的 dict 中,但是当我去检查时它写入的文件,而不是打印新的字典对,而是打印与以前相同的文件。

运行程序,你就会明白我的意思了。这里发生了什么事?显然它与我的 for 循环中的某些内容有关。

while True:
user = input("Enter username: ")
if user not in store:
    password = input("Enter password: ")
    store[user] = password

    with open('userLog.txt', 'a') as userLog:
        for k, v in store.items():
            str_keys = str(k)
            str_values = str(v)
            userPass = f"Username: {k} | Password: {v} \n"
            userLog.write(userPass)
            print(store)
            break

else:
    print('Username Taken!')
    continue

【问题讨论】:

  • 你的 for 循环只运行一次,因为你有一个 break 语句。你想每次都写整个商店吗?如果是这样,请删除 break 语句。您只想添加新用户/通行证对吗?那么就不需要for循环了,只需要在文件中写入userpassword即可。
  • 你能用一些代码把它写成答案吗?我是一个视觉学习武士
  • 直到我看到“武士”才注意到你的名字

标签: python python-3.x dictionary text with-statement


【解决方案1】:

感谢@alex,这就是我想要的。我的问题是 for 循环和 break 语句。原来我什至不需要 for 循环。

 store = {}

while True:
    user = input("Enter username: ")
    if user not in store:
        password = input("Enter password: ")
        store[user] = password

        with open('userLog.txt', 'a') as userLog:
            userLog.write(f"Username: {user} | Password: {password} \n")

    else:
        print('Username Taken!')
        continue

【讨论】:

  • “唤醒这个混蛋武士,你有一个 for 循环要烧掉”,
  • 很好,请注意,如果您在此 while 循环中没有其他内容,则不需要 continue 语句。
猜你喜欢
  • 1970-01-01
  • 2019-10-07
  • 2016-09-16
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-04-17
  • 2021-03-23
相关资源
最近更新 更多