首页 > 解决方案 > Windows FileNotFoundError: [Errno 2] 没有这样的文件或目录

问题描述

我想用'os.path.join'打开一个文件,文件存在,但是我打不开,报错"FileNotFoundError"

这是运行python3.6,在Windows10中使用PyCharm。

此函数中发生错误:

def get_encoder(model_name):
    with open(os.path.join('models', model_name, 'encoder.json'), 'r') as f:
        encoder = json.load(f)

输出是' FileNotFoundError: [Errno 2] No such file or directory: 'models\ \345M\ \encoder.json'

我的文件目录是' ...\models\345M\encoder.json '
函数定义为' ...\encode.py '

20190519230831.png

标签: python-3.x

解决方案


看来问题来自不包括正确的根文件夹。由于encoder.py文件在src文件夹内,并且路径modelssrc.

代码应该是:


def get_encoder(model_name):
    with open(os.path.join('..\\models', model_name, 'encoder.json'), 'r') as f:
        encoder = json.load(f)

让我知道这是否适合您。


推荐阅读