简体   繁体   中英

python: Unable to open json file from another directory?

My tests are at:

src/com/xyz/tests/api_test/<Test File>

My test file calls my libraries at:

src/com/xyz/libs/api_libs/<Library File>

My library file has to open a JSON file at:

src/com/xyz/libs/api_libs/configs/<Config File>

In my library file, since its at the same parent directory as the JSON configs, I have used the following code to open the JSON.

with open('configs/sample_wlan_json'):
    <Do Some action> 

I tried various paths like:

.../libs/api_libs/configs/<ConfigFileName>

src/com/mist/libs/api_libs/configs/<ConfigFileName>.json

The whole path from /Users/...... but nothing seems to work.

A relative path is relative to the current working directory. Current working directory depends on how an application is started, and not where it is.

So, if you want to have a path relative to your source code, you should not rely on the current working directory, but construct the absolute path instead.

You can construct a path which is relative to your source code by using the __file__ variable, which is the path to the current py file.

Something like this should work:

configs_dir = os.path.join(__file__, '..', 'configs')

with open(os.path.join(configs_dir, 'sample_wlan.json'), 'rt') as f:
   ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM