为什么在我尝试读取文件时会删除文件内容?开放函数python
好了,伙计们,我对编程还很陌生。我发现,我可以学习编写代码来编写一些东西,这些东西将来可能会有用,所以我编写了这段代码。我试着给自己两个选择1登录和2注册。当我注册一切正常时,它会将我的文本加密到sha256并写入文件,但当我尝试“登录”时,open read函数会删除文件login.txt的内容,因此检查逻辑上失败。提前谢谢你为什么在我尝试读取文件时会删除文件内容?开放函数python,python,file,sha256,Python,File,Sha256,好了,伙计们,我对编程还很陌生。我发现,我可以学习编写代码来编写一些东西,这些东西将来可能会有用,所以我编写了这段代码。我试着给自己两个选择1登录和2注册。当我注册一切正常时,它会将我的文本加密到sha256并写入文件,但当我尝试“登录”时,open read函数会删除文件login.txt的内容,因此检查逻辑上失败。提前谢谢你 import hashlib #Creating file to save token into. login_file = open("Login.t
import hashlib
#Creating file to save token into.
login_file = open("Login.txt", "w")
def register():
print("Please insert your token:")
reg_token = input()
#Encrypting and writing token into file.
login_file.write(hashlib.sha256(reg_token.encode()).hexdigest())
login_file.close()
print("Registration completed.")
def login():
token_file = open("Login.txt", "r").read()
print("Please login with your token:")
log_token = input()
#Calculating hash for input.
hash = hashlib.sha256(log_token.encode()).hexdigest()
#Comparing hashes.
if hash == token_file:
print("Success!")
if hash != token_file:
print("Login was unsuccessful.")
def prompt():
print("For login type 1. For registration type 2.")
prompt_input = input()
if prompt_input == "1":
login()
if prompt_input == "2":
register()
###############################################################################
prompt()
register()函数中
您每次都以写模式打开文件,即使您只想从中读取。第一行应该在函数
register
中。谢谢@chepner,它帮助了我。谢谢你,祝你度过愉快的一天。