[英]How to use the write/read log file
我是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()
todays_date
和reason_password_invalid
变量仅在主if
语句的else
块中定义,因此如果用户输入有效密码,您将获得所述异常。
仅当用户输入无效密码时才应写入日志文件:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.