Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python access to project root directory

Tags:

python

Below folder structure of my application:

rootfolder
          /subfolder1/
          /subfolder2
          /subfolder3/test.py

my code inside of the subfolder3. But I want to write output of the code to subfolder1.

script_dir = os.path.dirname(__file__)

full_path = os.path.join(script_dir,'/subfolder1/')

I would like to know how can I do this wihout importing full path to directory.

like image 873
Qaqa Leveo Avatar asked Dec 12 '17 22:12

Qaqa Leveo


People also ask

How do I get to the root directory in Python?

Getting the Current Working Directory in Python If you want to find the directory where the script is located, use os. path. realpath(__file__) . It will return a string containing the absolute path to the running script.

How do I get the project file path in Python?

You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .

Where is the root directory of a project?

The project root is the folder which is the parent for all the project sources. By default, all subfolders in this folder are treated as sources and their files are involved in indexing, searching, parsing, code completion, and so on. Use the icons on the toolbar to change this status.


1 Answers

It sounds like you want something along the lines of

project_root = os.path.dirname(os.path.dirname(__file__))
output_path = os.path.join(project_root, 'subfolder1')

The project_root is set to the folder above your script's parent folder, which matches your description. The output folder then goes to subfolder1 under that.

I would also rephrase my import as

from os.path import dirname, join

That shortens your code to

project_root = dirname(dirname(__file__))
output_path = join(project_root, 'subfolder1')

I find this version to be easier to read.

like image 145
Mad Physicist Avatar answered Oct 11 '22 22:10

Mad Physicist