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

Python代码读取文件触发FileNotFoundError的原因排查

解决Python读取文件时的FileNotFoundError问题

用户提供的代码如下:

file_name = input("Enter the file name: ")

# Open the file and read the data
with open(file_name, "r") as file:
    lines = file.readlines()

运行后触发FileNotFoundError,即便文件和脚本同目录或移到C盘根目录也无法识别,常见原因及解决办法如下:

  • 输入的文件名带多余空格:input()会原样读取用户输入的内容,要是输入时不小心在文件名前后加了空格(比如note.txt),程序会尝试读取带空格的文件名,自然找不到对应文件。可以给输入加个strip()处理:

    file_name = input("Enter the file name: ").strip()
    
  • 没输入完整的文件扩展名:比如文件实际是data.csv,你只输入了data,系统找不到匹配的文件。必须输入包含后缀的完整文件名,比如.txt、.csv这类后缀不能少。

  • 运行脚本的工作目录不对:就算文件和脚本在同一个文件夹,如果你运行脚本时的当前工作目录不是脚本所在的目录,相对路径就会失效。可以先打印当前工作目录确认:

    import os
    print(os.getcwd())
    

    解决办法要么切换到脚本所在目录再运行,要么用脚本的绝对路径拼接文件名,保证路径正确:

    import os
    # 获取脚本所在的绝对目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    file_name = input("Enter the file name: ").strip()
    # 拼接出文件的完整路径
    full_file_path = os.path.join(script_dir, file_name)
    with open(full_file_path, "r") as file:
        lines = file.readlines()
    
  • 系统隐藏了文件扩展名:Windows默认会隐藏已知文件类型的扩展名,比如你看到的文件名叫report,实际它的全名是report.txt,但系统没显示后缀。这时候你输入report肯定找不到文件,需要先在文件夹选项里取消“隐藏已知文件类型的扩展名”,再确认真实的文件名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:50:00