首页 > 解决方案 > 如何使用写/读日志文件

问题描述

我是 python 新手,我正在尝试编写一个程序,当每次用户输入错误/失败的密码尝试时,它都会将其写入文件中。其中记录了时间/日期及其无效的原因。然后应该显示输出。

我试过运行我的代码,但总是出现错误:

log_file.write({todays_date},{reason_password_invalid}) UnboundLocalError:分配前引用的局部变量“todays_date”

我不确定为什么会这样。我的代码是否没有正确写入,每次不正确时都能够写入文件?

import datetime

def main():
MIN_PASSWORD_LENGTH = 6
MAX_PASSWORD_LENGTH = 14
PASSWORD_LOG_FILE = "password_log.txt"
password = input("Enter your password: ")
password_length = len(password)

if password_length > MIN_PASSWORD_LENGTH and password_length < MAX_PASSWORD_LENGTH:

    if password.isalpha():
        message = "Your password is weak! It only contains letters."
    elif password.isnumeric():
        message = "Your password is weak! It only contains numbers."
    else:
        message = "Your password is strong! It contains letters and numbers."
else:
    my_date = datetime.datetime.today()
    todays_date = my_date.strftime("%A%B%d%Y")

    if password_length < MIN_PASSWORD_LENGTH:
        reason_password_invalid = "password_length < 6"
    else:
        reason_password_invalid = "password_length > 14"

log_file = open(PASSWORD_LOG_FILE, "a")
log_file.write({todays_date},{reason_password_invalid})
log_file.close()

log_file = open(PASSWORD_LOG_FILE, "r")
for line in log:
    print(line, end="")
log_file.close()
main()

标签: python

解决方案


和变量仅在主语句的块中定义todays_date,因此如果用户输入有效密码,您将收到上述异常。reason_password_invalidelseif

仅当用户输入无效密码时才应写入日志文件:

else:
    my_date = datetime.datetime.today()
    todays_date = my_date.strftime("%A%B%d%Y")

    if password_length < MIN_PASSWORD_LENGTH:
        reason_password_invalid = "password_length < 6"
    else:
        reason_password_invalid = "password_length > 14"

    log_file = open(PASSWORD_LOG_FILE, "a")
    log_file.write(f'{todays_date},{reason_password_invalid}\n')
    log_file.close()

推荐阅读