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

Python脚本无法读取用户名文件内容,此前正常现突发故障求助

问题描述

脚本无法识别用户名文件中的名称。

脚本可以找到该文件,只要稍微修改路径中的名称程序就无法运行,但无论如何都无法读取文件中的内容——我编写程序时它还能正常工作,现在突然失效了,文件位置也没有变化。
附:我不知道怎么在Stack Overflow上正确格式化代码

原始代码

filen = 'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
usern = open(filen, 'r')
userr = input("Enter your Username: ")
ass = input("Enter your Password: ")


def func():
    user = input("Enter new Username: ")
    passs = input("Enter new Password: ")
    passs1 = input("Confirm password: ")

    if passs != passs1:
        print("Passwords do not match!")
    else:
        if len(passs) <= 6:
            print("Your password is too short, restart:")

        elif user in usern:
            print("This username already exists")

        else:
            usern = open(filen, "a")
            usern.write(user+", "+passs+"\n")
            print("Success!")

while True:
    if userr not in usern:
        again = input("This username does not exist, would you like to try again? ")
        if again == ("No"):
            func()
        elif again == ("no"):
            func()
        elif again == ("Yes"):
            print("Try again:")
            userr = input("Enter your Username: ")
            ass = input("Enter your Password: ")
        elif again == ("yes"):
            print("Try again:")
            userr = input("Enter your Username: ")
            ass = input("Enter your Password: ")
        elif userr in usern:
            print("Good, you have entered the zone")
问题解决

1. 路径转义错误

Windows路径里的\在Python字符串中是转义字符,比如\U会被解析为Unicode转义,直接导致路径识别异常。三种解决方式:

  • 用双反斜杠替换:filen = 'C:\\Users\\fabby\\Documents\\Extra Things I Might Need\\Port Folio Stuff\\Python\\usernames'
  • 用原始字符串(引号前加r):filen = r'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'
  • 用正斜杠替代:filen = 'C:/Users/fabby/Documents/Extra Things I Might Need/Port Folio Stuff/Python/usernames'

2. 文件内容读取逻辑错误

你直接用user in usern是检查字符串是否在文件对象里,而非文件内容中。必须先读取文件内容才能做判断:

  • 读取所有内容并拆分用户列表:with open(filen, 'r') as f: existing_users = [line.split(',')[0].strip() for line in f],之后用user in existing_users做检查
  • 注意:文件指针读取一次后会停在末尾,重复读取前需要重新打开文件或移动指针

3. 文件操作规范

直接open()文件后不关闭会导致资源泄漏,建议用with语句自动管理文件生命周期,避免此类问题。

修正后的完整代码

filen = r'C:\Users\fabby\Documents\Extra Things I Might Need\Port Folio Stuff\Python\usernames'

def func():
    user = input("Enter new Username: ")
    passs = input("Enter new Password: ")
    passs1 = input("Confirm password: ")

    if passs != passs1:
        print("Passwords do not match!")
        return
    if len(passs) <= 6:
        print("Your password is too short, restart:")
        return
    
    # 读取现有用户名列表
    with open(filen, 'r') as f:
        existing_users = [line.split(',')[0].strip() for line in f.readlines()]
    if user in existing_users:
        print("This username already exists")
        return
    
    # 写入新用户信息
    with open(filen, "a") as f:
        f.write(f"{user}, {passs}\n")
        print("Success!")

while True:
    userr = input("Enter your Username: ")
    ass = input("Enter your Password: ")
    
    # 验证用户是否存在
    with open(filen, 'r') as f:
        existing_users = [line.split(',')[0].strip() for line in f.readlines()]
    if userr not in existing_users:
        again = input("This username does not exist, would you like to try again? ")
        if again.lower() == "no":
            func()
            break
        elif again.lower() == "yes":
            print("Try again:")
        else:
            print("Invalid input, please enter Yes or No")
    else:
        print("Good, you have entered the zone")
        break

Stack Overflow代码格式化方法

  • 单行代码:用单个反引号包裹,比如print("hello world")
  • 多行代码块:在代码前后各加三个反引号(),开头的反引号后可指定语言(比如python),实现语法高亮

内容的提问来源于stack exchange,提问作者Noodle Head117

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:41:56