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

VS22中Python项目内标记为Content的txt文件找不到问题求助

Python文件找不到错误的原因及解决办法

错误信息:

Message=[Errno 2] No such file or directory: 'frankenstein.txt'
Source=C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8\homework8.py
StackTrace:
File "C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8\homework8.py", line 171, in create_ngram_model
    with open(path, "r") as f:
File "C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8\Test.py", line 72, in <module>
    m = create_ngram_model(1, "frankenstein.txt"); m.random_text(15)

无法定位文件的原因:

  • Python默认按当前工作目录(运行脚本时所在的目录)查找文件,不是脚本本身所在的目录。你运行Test.py时,当前工作目录可能不是Homework8文件夹,直接用文件名自然找不到。
  • 解决方案资源管理器里把文件设为Content只是IDE的配置,和Python运行时的路径查找逻辑无关,不会帮Python定位文件。

正确解决办法:

你用os.path.join(os.path.dirname(__file__), 'frankenstein.txt')的方法其实就是标准的正确方案,另外还有几种等价的实现方式:

  1. 推荐:用__file__或pathlib构建绝对路径
    传统os模块写法:
    import os
    # 获取脚本所在目录,拼接文件名得到绝对路径
    file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'frankenstein.txt')
    with open(file_path, "r") as f:
        # 处理文件
    
    Python 3.4+可以用pathlib更简洁:
    from pathlib import Path
    file_path = Path(__file__).parent / 'frankenstein.txt'
    with open(file_path, "r") as f:
        # 处理文件
    
  2. 切换当前工作目录到脚本所在位置
    import os
    # 切换工作目录到脚本所在文件夹
    os.chdir(os.path.dirname(os.path.abspath(__file__)))
    # 之后直接用文件名打开即可
    with open("frankenstein.txt", "r") as f:
        # 处理文件
    
  3. 运行脚本时指定正确工作目录
    在命令行先进入Homework8文件夹,再运行脚本:
    cd C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8
    python Test.py
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:30:56