Search code examples
pythonfilepathreadfileabsolute-path

Python directory file go wrong


I am having a silly problem with reading a file in python.

I have a folder 'a' that contains my test.py and file test.json for reading.

My test.py looks like this:

config_path = 'test.json'
with open(config_path) as config_buffer:
    config = json.loads(config_buffer.read())

When I go outside the directory structure of folder 'a' and I run the command:

python a\test.py

And the console returns this error:

FileNotFoundError: No such file or directory: 'test.json'

I try using the absolute file path using pathlib:

config_path = Path('end2end.json').absolute()
with open(config_path) as config_buffer:
    config = json.loads(config_buffer.read())

But it still returns this error to me:

FileNotFoundError: No such file or directory: 'D:\\test.json'

Can anyone help me to get exactly the right directory file?


Solution

  • If you want to call your python script from any folder and let it access its local files without specifying paths, you can change the directory in the begining:

    import os
    os.chdir(os.path.dirname(os.path.realpath(__file__)))
    
    config_path = 'test.json'
    ...