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

Python报错Errno 2:无法找到user.txt文件求助

问题求助:无法读取同目录下的user.txt和passw.txt文件

问题描述

我是Python新手,运行代码时遇到错误:Errno 2 No such file or directory: 'user.txt'。明明user.txt和passw.txt与Python脚本在同一目录,但Python就是识别不到这些文件。我试过谷歌搜索、本站其他解决方案,还换过文件名,都没用,请求帮忙实现对这两个文件的读写功能。

IDE目录截图显示脚本与user.txt、passw.txt处于同一目录。

我的代码

question1 = input(" Do You Have a User Account? Yes or No ")
if question1 == ('y') or ("Yes") or ("yes") or ("Y"):
    question1 = ('n')
elif question1 == ('n') or ("No") or ("no") or ("N"):
    question1 = ('y')
else:
    print (' That is not an option ')

user = open("user.txt")
read1 = user.read()

passw = open("passw.txt")
read2 = passw.read()


if question1 == ("y"):

    user = open("user.txt")

    read1 = user.read()



    user.close

    user = open("user.txt","a+")
    x = input("please enter a username ")
    user.write("\n")

    user.write(x)


    passw = open("passw.txt")

    read2 = passw.read()



    passw.close

    passw = open("passw.txt","a+")
    x = input("please enter a password ")
    passw.write("\n")

    passw.write(x)
else:
    print(" wait a second please")

score = (0)

user = input("please enter your username ")
user = open("user.txt","r")
read1 = user.read()
if user in read1:
    print("yes")
    score =+ (1)
    user.close()
else:
    print("no")


if score == (1):
    print("Please Continue")

解决方案

1. 解决文件路径问题

Python脚本运行时的工作目录不一定是脚本所在目录,这是核心原因。两种修复方式:

  • 方法一:用绝对路径加载文件
    在代码开头添加以下代码,自动获取脚本所在目录并拼接文件路径,确保不会找错位置:

    import os
    # 获取脚本所在目录的绝对路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    # 拼接文件的完整路径
    user_file = os.path.join(script_dir, "user.txt")
    passw_file = os.path.join(script_dir, "passw.txt")
    

    后续所有操作文件的地方,把"user.txt"换成user_file,"passw.txt"换成passw_file即可。

  • 方法二:在IDE中设置工作目录
    打开IDE的运行配置(比如VS Code的 launch.json、PyCharm的运行配置),将工作目录设置为脚本所在的文件夹。

2. 修复代码中的其他错误

你的代码还有几个逻辑问题,即使找到文件也会出错:

  • 条件判断逻辑错误:原代码中if question1 == ('y') or ("Yes")...永远为True,因为("Yes")本身是布尔值True。正确写法:
    if question1.lower() in ['y', 'yes']:
        question1 = 'n'
    elif question1.lower() in ['n', 'no']:
        question1 = 'y'
    else:
        print(' That is not an option ')
    
  • 文件未正确关闭:user.close没有加括号,不会执行关闭操作。推荐用with语句自动管理文件,避免遗漏:
    # 读取文件示例
    with open(user_file, 'r') as f:
        read1 = f.read()
    
    # 追加写入文件示例
    with open(user_file, 'a+') as f:
        x = input("please enter a username ")
        f.write(f"\n{x}")
    
  • 变量名冲突:代码中user = input(...)之后又把user赋值为文件对象,覆盖了输入的用户名,导致if user in read1:判断失效。要换不同的变量名:
    username_input = input("please enter your username ")
    with open(user_file, 'r') as f:
        read1 = f.read()
    if username_input in read1:
        print("yes")
        score += 1
    else:
        print("no")
    
  • 赋值错误:score =+ (1)应该是score += 1,前者会直接把score设为1,后者是在原有值基础上加1。

修正后的完整代码

import os

# 获取脚本所在目录并拼接文件路径
script_dir = os.path.dirname(os.path.abspath(__file__))
user_file = os.path.join(script_dir, "user.txt")
passw_file = os.path.join(script_dir, "passw.txt")

question1 = input(" Do You Have a User Account? Yes or No ")
if question1.lower() in ['y', 'yes']:
    question1 = 'n'
elif question1.lower() in ['n', 'no']:
    question1 = 'y'
else:
    print(' That is not an option ')

# 初始化文件内容(文件不存在则创建空内容)
try:
    with open(user_file, 'r') as f:
        read1 = f.read()
    with open(passw_file, 'r') as f:
        read2 = f.read()
except FileNotFoundError:
    read1 = ""
    read2 = ""

if question1 == "y":
    # 写入用户名
    with open(user_file, 'a+') as f:
        x = input("please enter a username ")
        f.write(f"\n{x}")
    # 写入密码
    with open(passw_file, 'a+') as f:
        x = input("please enter a password ")
        f.write(f"\n{x}")
else:
    print(" wait a second please")

score = 0

username_input = input("please enter your username ")
with open(user_file, 'r') as f:
    read1 = f.read()
if username_input in read1:
    print("yes")
    score += 1
else:
    print("no")

if score == 1:
    print("Please Continue")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:18:23