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')的方法其实就是标准的正确方案,另外还有几种等价的实现方式:
- 推荐:用
__file__或pathlib构建绝对路径
传统os模块写法:
Python 3.4+可以用pathlib更简洁:import os # 获取脚本所在目录,拼接文件名得到绝对路径 file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'frankenstein.txt') with open(file_path, "r") as f: # 处理文件from pathlib import Path file_path = Path(__file__).parent / 'frankenstein.txt' with open(file_path, "r") as f: # 处理文件 - 切换当前工作目录到脚本所在位置
import os # 切换工作目录到脚本所在文件夹 os.chdir(os.path.dirname(os.path.abspath(__file__))) # 之后直接用文件名打开即可 with open("frankenstein.txt", "r") as f: # 处理文件 - 运行脚本时指定正确工作目录
在命令行先进入Homework8文件夹,再运行脚本:cd C:\Users\richy\OneDrive\Documents\Python Scripts\CIS 521\CIS 521\CIS 521\Homework8 python Test.py
内容的提问来源于stack exchange,提问作者Da_Overloaded_Dad
相关产品推荐
相关产品推荐

