简体   繁体   English

从文本文件中读取用户名和密码

[英]read username and password from text file

I am trying to make a username and password that gets taken from a text file.我正在尝试创建一个从文本文件中获取的用户名和密码。 The username and password is added at the beginning and used after.用户名和密码在开头添加并在之后使用。 I add a username and password at the start and it works.我在开始时添加了用户名和密码,它可以工作。 It adds it to the text document but it says that it isn't on the document when i enter the 2 previously created credentials.它将它添加到文本文档中,但是当我输入 2 个以前创建的凭据时,它说它不在文档中。 I put the part i belive is giving issues in **.我把我相信的部分放在**中。 Any way to make this work properly?有什么办法可以使它正常工作? If my point isn't clear i can specify more if necessary.如果我的观点不清楚,我可以在必要时指定更多。 Thanks.谢谢。

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

saveFile.write writes to the end of the file, so the file cursor points to the end of the file. saveFile.write写入文件末尾,因此文件光标指向文件末尾。
saveFile.read() reads from the current position to the end ( docs ). saveFile.read()从当前位置读取到末尾( docs )。

You need to move the file cursor to the beginning of the file, before reading:在阅读之前,您需要将文件光标移动到文件的开头:

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)

Out:出去:

foo
bar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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