Python报错AttributeError: 'str' object has no attribute 'write'排查求助
报错原因与修复方案
核心错误原因
你触发报错的根本原因是混淆了文件名字符串和文件操作对象:
- 你定义的
PASSWORD_LOG_FILE = "password_log_Nicholas_Webb.txt"是存储文件路径的字符串类型变量,本身没有write()、close()这类文件操作方法 - 执行
open(PASSWORD_LOG_FILE, "a")打开文件时,你没有把open函数返回的文件操作对象赋值给变量,后续直接对字符串变量调用write方法才触发了AttributeError: 'str' object has no attribute 'write'报错
其他存在的问题
- open操作写在了while循环内部,每次密码校验失败都会重复打开文件,属于冗余操作
- 手动调用
close()关闭文件的写法,如果程序中途运行异常会导致文件无法正常关闭,更推荐使用with上下文管理器自动处理文件的打开和关闭
修正后的完整代码
def main(): import datetime print("PasswordChecker3 program developed by: Nicholas Webb") MIN_PASSWORD_LENGTH = 6 MAX_PASSWORD_LENGTH = 10 PASSWORD_LOG_FILE = "password_log_Nicholas_Webb.txt" curr_date_and_time = datetime.datetime.today() password = input("Enter Password: ") password_len = len(password) # 提前打开日志文件,用with上下文管理器自动处理关闭 with open(PASSWORD_LOG_FILE, "a") as log_file: while password_len < MIN_PASSWORD_LENGTH or password_len > MAX_PASSWORD_LENGTH: print(f"Your Password has {password_len} characters, Password length needs to be between {MIN_PASSWORD_LENGTH} and {MAX_PASSWORD_LENGTH} characters long.") if password_len < MIN_PASSWORD_LENGTH: print(f"password length is {password_len} characters long.") invalid_password_reason = "password < 6" # 用文件对象执行写入操作 log_file.write("{a}, {b} characters".format(a=curr_date_and_time, b=invalid_password_reason)) log_file.write("\n") else: print(f"password length is {password_len} characters long.") invalid_password_reason = "password > 10" log_file.write("{a}, {b} characters".format(a=curr_date_and_time, b=invalid_password_reason)) log_file.write("\n") password = input("re-enter password: ") password_len = len(password) if password.isnumeric(): print("Password weak - Contains only numbers") elif password.isalpha(): print("Password weak - Contains only letters") else: print("Password strong") if __name__ == "__main__": main()
内容的提问来源于stack exchange,提问作者Erebus92
相关产品推荐
相关产品推荐

