Home > Enterprise >  How to get the path of a sub folder under root directory of the project in python?
How to get the path of a sub folder under root directory of the project in python?

Time:09-13

Had to post this question again as my previous one was closed saying that my question wasn't focused. So here by I'm trying again.

My Folder structure looks like this:

root_folder:
    - core
    - files
    - solution
        - sub_folder
             - test.py 
    - tests

I need to get the absolute path of sub folder files from the python file test.py.

Have tried various ways using os.path.abs and os.path.dirname but did not work for me.

Any help could be appreciated.

Tested code and output:

print(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'files'))

output: /home/kulasangar/Documents/bst_work/root_folder/solution/files

expected output: /home/kulasangar/Documents/bst_work/root_folder/files

CodePudding user response:

You can use sys.path to access the root of your project from everywhere in your code.

import sys
print('My nested folder : ', os.getcwd())
print('File name : ', os.path.basename(__file__))
print('Root path:', sys.path[1])

Assuming the same folder structure you posted, my project folder is named testing . So, the output is

My nested folder :  /Users/hellbreak/Documents/Coding/Python Lab/testing/solutions/sub_folder
File name :  test.py
Root path: /Users/hellbreak/Documents/Coding/Python Lab/testing

Then, if you are interested in a particular path, you can

print('My nested folder : ', os.getcwd())
print('File name : ', os.path.basename(__file__))
print('Root path:', sys.path[1] '/files')

The output:

My nested folder :  /Users/hellbreak/Documents/Coding/Python Lab/testing/solutions/sub_folder
File name :  test.py
Root path: /Users/hellbreak/Documents/Coding/Python Lab/testing/files

CodePudding user response:

On top of @hellbreak's answer, I figured out another way:

from pathlib import Path
import os

current_dir = Path(__file__)
project_root_dir_path = [p for p in current_dir.parents if p.parts[-1] == 'root_folder'][0]
files_path = os.path.join(project_root_dir_path, 'files')
  • Related