Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在我尝试读取文件时会删除文件内容?开放函数python_Python_File_Sha256 - Fatal编程技术网

为什么在我尝试读取文件时会删除文件内容?开放函数python

为什么在我尝试读取文件时会删除文件内容?开放函数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

好了,伙计们,我对编程还很陌生。我发现,我可以学习编写代码来编写一些东西,这些东西将来可能会有用,所以我编写了这段代码。我试着给自己两个选择1登录和2注册。当我注册一切正常时,它会将我的文本加密到sha256并写入文件,但当我尝试“登录”时,open read函数会删除文件login.txt的内容,因此检查逻辑上失败。提前谢谢你

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()函数中

  • 用于确定如何处理文件的第二个参数<代码>“w”首先删除内容<代码>“a”将允许您附加到文件中


  • 您每次都以写模式打开文件,即使您只想从中读取。第一行应该在函数
    register
    中。谢谢@chepner,它帮助了我。谢谢你,祝你度过愉快的一天。