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

Python刷题练习程序遭遇FileNotFoundError问题求助

问题:Python刷题程序持续出现FileNotFoundError无法解决

我编程经验较少,尝试制作一款基于.txt题库的Python刷题练习程序。题库格式要求:

  • 每行开头数字为题号,后续为题干
  • 答案行以+/-标识对错(+为正确,-为错误)

程序需实现的功能:

  • 随机抽题
  • 选取4个随机答案
  • 用户输入+/-判断对错后程序给出反馈

但运行时始终出现FileNotFoundError错误,尽管已将data.txt与代码保存在桌面同一目录、设置读取权限,且尝试修改读取函数、使用绝对路径等方法,问题仍未解决。附上代码如下:

def load_questions(file_path):
    questions = []
    with open(file_path, 'r', encoding='utf-8') as f:
        lines = f.readlines()
        question = {}
        for line in lines:
            if line.strip() == '':
                continue
            if line[0].isdigit():
                if question:
                    questions.append(question)
                question = {'text': line.strip(), 'answers': []}
            else:
                answer = {'text': line[1:].strip(), 'correct': line[0] == '+'}
                question['answers'].append(answer)
        if question:
            questions.append(question)
    return questions

def display_question(question):
    print(question['text'])
    for i, answer in enumerate(question['answers']):
        print(f"{i}. {answer['text']}")

def get_user_answers(question):
    user_answers = []
    for i, answer in enumerate(question['answers']):
        while True:
            user_input = input(f"Is answer {i} correct or incorrect? (+/-): ")
            if user_input == '+' or user_input == '-':
                user_answers.append(user_input == '+')
                break
            else:
                print("Invalid input. Please enter + or -.")
    return user_answers

def display_results(question, user_answers):
    for i, answer in enumerate(question['answers']):
        if answer['correct'] == user_answers[i]:
            print(f"{answer['text']} - Correct")
        else:
            print(f"{answer['text']} - Incorrect")

def main():
    file_path = r'C:\Users\thejy\OneDrive\Desktop\data.txt'
    questions = load_questions(file_path)
    while True:
        question = random.choice(questions)
        random.shuffle(question['answers'])
        display_question(question)
        user_answers = get_user_answers(question)
        display_results(question, user_answers)
        input("Press enter to continue...")

if __name__ == '__main__':
    main()

恳请提供帮助与指导。


解决方案

一、优先排查文件路径问题

  1. 验证绝对路径准确性
    • 手动打开C:\Users\thejy\OneDrive\Desktop\目录,确认data.txt存在,注意检查文件名拼写(比如是否因系统隐藏后缀名导致实际为data.txt.txt)
    • 复制文件实际绝对路径:右键data.txt→属性→安全→对象名称,复制完整路径替换代码中的file_path
  2. 处理OneDrive同步异常
    OneDrive同步延迟可能导致文件暂时不可用,可将data.txt移至非OneDrive目录(如C:\temp\)测试,或关闭OneDrive同步后重新放置文件

二、代码层面修复与优化

  1. 添加文件存在性检查
    在load_questions函数开头增加检查,明确报错信息:
    import os
    def load_questions(file_path):
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"文件未找到,请检查路径:{file_path}")
        if not os.path.isfile(file_path):
            raise ValueError(f"指定路径不是文件:{file_path}")
        # 原函数剩余代码...
    
  2. 补全缺失的模块导入
    代码使用了random模块但未导入,在代码最开头添加:
    import random
    
  3. 实现随机选取4个答案的功能
    原代码仅打乱答案顺序,未实现选取4个随机答案的需求,修改main函数逻辑:
    def main():
        file_path = r'C:\Users\thejy\OneDrive\Desktop\data.txt'
        questions = load_questions(file_path)
        while True:
            question = random.choice(questions)
            # 随机选取4个答案(若答案数量超过4)
            if len(question['answers']) > 4:
                selected_answers = random.sample(question['answers'], 4)
            else:
                selected_answers = question['answers'].copy()
            random.shuffle(selected_answers)
            # 构造临时问题对象用于展示
            temp_question = {'text': question['text'], 'answers': selected_answers}
            display_question(temp_question)
            user_answers = get_user_answers(temp_question)
            display_results(temp_question, user_answers)
            input("Press enter to continue...")
    

三、其他排查方向

  • 检查data.txt是否被其他程序占用(如记事本、WPS等未关闭)
  • 尝试以管理员权限运行Python脚本,避免系统权限限制

内容的提问来源于stack exchange,提问作者Jakub Lukáč

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 13:05:08