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

Python运行报FileNotFoundError找不到同目录下文件该如何解决?

问题原因
  • 工作目录不匹配:Python运行时的当前工作目录(CWD) 不是源代码所在的文件夹,相对路径是基于CWD计算的,而非基于py文件的存放路径。比如用IDE打开项目根目录但py文件存放在子文件夹中,或者终端运行时切换到了其他目录执行脚本,都会触发该报错。
  • 路径拼写/大小写问题:Linux、macOS系统下路径大小写敏感,Sentiment_dicts和sentiment_dicts会被识别为不同路径,需检查sentiment_dicts文件夹名、三个txt文件名的拼写、大小写和实际是否完全一致。
  • 文件夹层级错误:需确认py文件同级目录下确实存在sentiment_dicts文件夹,三个txt文件存放在该文件夹内部,而非和py文件直接放在同级目录。
解决方案
  • 方案1:调整运行时工作目录
    终端运行脚本前,先cd到py文件所在的文件夹,再执行python 你的脚本名.py;如果使用IDE运行,可以在对应脚本的运行配置中,将工作目录设置为当前py文件的存放目录。
  • 方案2:使用绝对路径定位(最稳妥,不受运行位置影响)
    借助os模块先获取当前py文件的绝对路径,再拼接目标文件的相对路径,修改后代码示例:
import os
import codecs

# 获取当前py文件所在文件夹的绝对路径
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# 拼接得到目标文件的绝对路径
path_nag = os.path.join(BASE_DIR, 'sentiment_dicts', 'nag.txt')
path_pos = os.path.join(BASE_DIR, 'sentiment_dicts', 'pos.txt')
path_not = os.path.join(BASE_DIR, 'sentiment_dicts', 'not.txt')

with codecs.open(path_nag, 'r', encoding='UTF-8') as f:
    nag = f.readlines()
nag_list = [n.replace('\n', '') for n in nag]
with codecs.open(path_pos, 'r', encoding='UTF-8') as f:
    pos = f.readlines()
pos_list = [n.replace('\n', '') for n in pos]
with codecs.open(path_not, 'r', encoding='UTF-8') as f:
    not_ = f.readlines()
not_list = [n.replace('\n', '') for n in not_]
  • 方案3:核对路径与文件结构
    逐字符核对文件夹、文件的拼写与大小写,确保文件层级符合以下结构:
    脚本所在文件夹/
    ├── 你的脚本名称.py
    └── sentiment_dicts/
        ├── nag.txt
        ├── pos.txt
        └── not.txt
    

内容的提问来源于stack exchange,提问作者Phạm Hồ Nguyễn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:45:00