【问题标题】:Why is content of my file deleted when i try to read it? open function python为什么当我尝试阅读我的文件内容时会删除它?打开函数python
【发布时间】:2021-03-25 01:25:31
【问题描述】:

好的,伙计们,我对编程很陌生。我发现,我可以学习编写一些代码,这些代码将来可能会真正有用,所以我编写了这个代码。我试图给自己 2 个选项 1 登录和 2 注册。当我注册一切正常时,它将我的文本加密为 sha256 并将其写入文件,但是当我尝试“登录”时,打开读取功能会删除文件 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 内。
  • 谢谢@chepner,它帮助了我。

标签: python file sha256


【解决方案1】:
  1. 你第一次打开文件的那一行应该在register()函数里面。

  2. open() 的第二个参数决定了文件的处理方式。 ”w” 先删除内容。 ”a” 将允许您附加到文件。

【讨论】:

  • 谢谢,祝您有美好的一天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-13
  • 1970-01-01
  • 2015-03-10
相关资源
最近更新 更多