如何使用写/读日志文件

时间:2019-04-02 00:08:22

标签: python

我是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()

1 个答案:

答案 0 :(得分:0)

todays_datereason_password_invalid变量仅在主else语句的if块中定义,因此,如果用户输入有效的字符串,则会得到上述异常密码。

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

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()