简体   繁体   中英

Python compute the path of file to open

Currently, I have a folder structure as below in my python project and I wanted to open the sample.json file in the run.py file.

parent_folder
    --subfolder1
        --sub_sub_folder1
            --sub_sub_sub_folder1
                --run.py
        -- sub_sub_folder2
            --sample.json

So I have tried as below

file_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'../../sub_sub_folder2/sample.json')
file_content= open(file_dir)

But I am getting error as below

[Errno 2] No such file or directory: '/usr/local/lib/python3.6/site-packages/sub_sub_folder2/sample.json'

Could some please help me?

You can first change the directory into where your python program exists through os.chdir :

os.chdir(os.path.dirname(os.path.abspath(__file__)))

And then, specify the path of your target file:

file_dir = '../../sub_sub_folder2/sample.json'

Your way to do it seems ugly to me, but it should work. Are you sure, the folder structure is as you describe it? The ErrorMessage implies that the parent folder of your project is /usr/local/lib/python3.6/ - that most probably not true.

A cleaner way would make use of pathlib

from pathlib import Path

path_script = Path(__file__)
path_ancestor_common = path_script.parents[2]
path_json = path_ancestor_common.joinpath(
    'sub_sub_folder2', 'sample.json')

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