FileNotFoundError: [Errno 2] No such file or directory But I already have the file and directory

Question:

I’ve created this project structure, I’ve written a py file under lines

- Report
  - rep
    - common
    - config
    - Lines
    - static
    - templates

as follows

import yaml

def read_conf(env='default'):
    data_list = {} # 存储配置
    with open(r"../config/database.yaml", 'r', encoding='utf-8') as ymlfile:
        cfg = yaml.load_all(ymlfile, Loader=yaml.SafeLoader)
        for data in cfg:
            data_list.update(data)
    if env == 'pro':
        re = data['conf']['pro']
        return re
    re = data['conf'][data[env]]
    return re
if __name__ == '__main__':
    re = read_conf()
    print(re)

By running this file directly, I can read the database.yaml file in the config directory, but when I call this function elsewhere, I get an error

FileNotFoundError: [Errno 2] No such file or directory: '../config/database.yaml'

I wonder what’s the reason for this

expected to happen:
I expect that I can call this function from another file and still get the result

{'host': '', 'user': '', 'passwd': '', 'db': '', 'port': }

actually resulted:

FileNotFoundError: [Errno 2] No such file or directory: '../config/database.yaml'

I use windows

Asked By: Rain

||

Answers:

You might want try to change the relative path to absolute path.

import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')

Relative paths in Python

Answered By: Danna
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.