Skip to main content
 首页 » 编程设计

Python:找不到 os.listdir 文件

2025年04月02日9sharpest

<分区>

我最近将我的配置文件移到了项目中的另一个文件夹中。我尝试加载这样的:

CONFIG_PATH = os.path.abspath(os.path.dirname(os.path.abspath(__file__))+"/../config/")     
 
def load_config(): 
    configs = {} 
    for config in os.listdir(CONFIG_PATH): 
        configs[str(config)[0:-12]] = json.load(open(config)) 
    return configs 

我正在运行代码

D:/.../MyProject/src 

并且指定的CONFIGPATH被正确设置为

D:/.../MyProject/config 

现在在该迭代循环中,open(config) 引发异常:

FileNotFoundError: [Errno 2] No such file or directory: 'sample.config.json' 

我不明白为什么我的程序不能打开一个文件,这个文件显然必须存在,因为它是由 os.listdir 给出的。实际上,循环中的 print(config) 确认存在具有该名称的文件。那么为什么它不打开而是引发 FileNotFoundError?

我是否错过了这里显而易见的内容?该代码在我向上移动文件之前起作用。我正在 Windows 7 上使用 Pycharm,如果有任何相关性的话。