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()
解决方案
和变量仅在主语句的块中定义todays_date
,因此如果用户输入有效密码,您将收到上述异常。reason_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()
推荐阅读
- node.js - 如何在nodejs中为完全不同的会话设置不同的会话表
- cytoscape - Cytoscape 中具有相对距离的细胞邻域分析
- c - 在间隔期间运行另一个函数时每秒调用一个函数
- reactjs - react-stomp-hooks useStompClient hook 在页面刷新时设置为 undefined
- r - 如何在 stargazer R 中编辑固定效果行?
- python - 如何使用 model.predict_proba() 加载模型
- javascript - 提交按钮然后刷新页面的脚本
- css - Nginx react子目录css js位置
- amazon-web-services - 在 Lambda 而不是 EC2 上为 AWS Glue 使用 ETL
- azure - 如何将第二行设置为标题?(Azure 数据工厂)