You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python加密登录脚本报错求助:存储信息至.data文件失败

Python登录脚本报错修复方案

问题排查

你的代码主要存在三个核心问题:

  • 缩进错误导致作用域失效:create_account和login函数的核心逻辑没有缩进在函数体内,导致调用函数时完全不执行对应操作,还会触发变量未定义的报错。
  • 文件关闭语句拼写错误:data.file.close()是笔误,正确写法是data_file.close()。
  • 密码比对的换行符干扰:读取存储的密码时,readline()会保留文本末尾的换行符,直接和加密后的密码比对会不匹配,需要清除换行符。

修正后的完整代码

import os
import hashlib

def encrypt_password(password):
    encrypted_password = hashlib.sha256(password.encode()).hexdigest()
    return encrypted_password

def create_account(username, password):
    encrypted_password = encrypt_password(password)
    # 缩进修正:文件操作逻辑放入函数体内
    data_file = open(username + '.data', 'w')
    data_file.write(username + '\n')
    data_file.write(encrypted_password)
    # 修正拼写错误:data_file而非data.file
    data_file.close()
    print('Account successfully created!')

def login(username, password):
    encrypted_password = encrypt_password(password)
    # 缩进修正:登录验证逻辑放入函数体内
    if os.path.exists(username + '.data'):
        data_file = open(username + '.data', 'r')
        stored_username = data_file.readline().rstrip('\n')
        # 清除密码行的换行符,避免比对失败
        stored_password = data_file.readline().rstrip('\n')
        data_file.close()
        
        if username == stored_username and encrypted_password == stored_password:
            print('Login successful!')
        else:
            print('Incorrect username or password')
    else:
        print('Account does not exist. Please create an account first.')

user_input = input('Do you want to create (c) or login (l) to an account? ')

if user_input == 'c':
    username = input('Enter username: ')
    password = input('Enter password: ')
    create_account(username, password)
elif user_input == 'l':
    username = input('Enter username: ')
    password = input('Enter password: ')
    login(username, password)
else:
    print('Invalid input')

额外优化建议

  • 建议使用with语句操作文件,它会自动关闭文件,避免手动关闭时的遗漏或错误:
    # 示例:create_account函数内的文件操作改用with
    with open(username + '.data', 'w') as data_file:
        data_file.write(username + '\n')
        data_file.write(encrypted_password)
    

内容的提问来源于stack exchange,提问作者user20733481

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:20:32