You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:21:00