Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: os.listdir files are not found [duplicate]

Tags:

python

json

file

I recently moved my config files to another folder in my Project. I try to load the like this:

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

I'm running the code from

D:/.../MyProject/src

And the specified CONFIGPATH is correctly set to

D:/.../MyProject/config

Now in that iteration loop, the open(config) raises an exception:

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

I can't see why my program can't open a file, which clearly has to exist since it is given out by os.listdir. Actually, a print(config) in the loop confirms that there is a file with that name. So why won't it open and instead raises a FileNotFoundError?

Do I miss the obvious here? The code worked before I moved the files upwards. I'm working with Pycharm on Windows 7, if that is of any relevance.

like image 626
Domino Avatar asked Apr 09 '26 21:04

Domino


1 Answers

os.listdir only return the name of the file, not the complete path.

If you're on 3.5 you can use os.scandir where the returned item has a path attribute. If you're not that lucky, you'll have to construct the full path yourself.

It would be: json.load(open(os.path.join(CONFIG_PATH, config))) in your case.

like image 64
sdlarsen Avatar answered Apr 12 '26 12:04

sdlarsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!