【问题标题】:read username and password from text file从文本文件中读取用户名和密码
【发布时间】:2021-12-22 14:34:27
【问题描述】:

我正在尝试创建从文本文件中获取的用户名和密码。用户名和密码在开头添加并在后面使用。我在开始时添加了用户名和密码,它可以工作。它将它添加到文本文档中,但它说当我输入 2 个先前创建的凭据时它不在文档上。我把我相信的部分放在**中。有什么办法可以正常工作吗?如果我的观点不清楚,我可以在必要时指定更多。谢谢。

import time
import sys

text1 = input("\n Write username ")
text2 = input("\n Write password ")
saveFile = open('usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
uap = saveFile.read()
saveFile.close()
max_attempts = 3
attempts = 0

while True:
    print("Username")
    username = input("")

    print("Password")
    password = input("")

    *if username in uap and password in uap:
        print("Access Granted")*
    else:
        attempts+=1
        if attempts >= max_attempts:
            print(f"reached max attempts of {attempts} ")
            sys.exit()
        print("Try Again (10 sec)")
        time.sleep(10)
        continue
    break

【问题讨论】:

  • 打印uap 看看它是什么。
  • 你试过用.readlines()代替.read()吗?

标签: python passwords


【解决方案1】:

saveFile.write 写入文件末尾,因此文件光标指向文件末尾。
saveFile.read() 从当前位置读取到末尾 (docs)。

您需要将文件光标移动到文件的开头,然后才能阅读:

text1 = 'foo'
text2 = 'bar'

saveFile = open('/tmp/usernames+passwords', 'r+')
saveFile.write('\n' + text1 + '\n' + text2 + '\n')
saveFile.seek(0)
uap = saveFile.read()
print(uap)

输出:

foo
bar

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 2014-10-06
    • 1970-01-01
    • 2023-04-05
    相关资源
    最近更新 更多