Python access to project root directory
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.
Finding File Relative to Project Root in Python
This would be a different answer if it were results.py
and the question were "How do you import that from here," but "How do you load that" is pretty straightforward.
Remember that __file__
is the relative path from your curdir to the python file it's being executed in. This lets us calculate the path in two ways: one using the modern pathlib
stdlib library and one with os
commands.
# using pathlib
from pathlib import Path
thisfile = Path(__file__)
programs = thisfile.parent
project1 = programs.parent
data = project1 / 'data' # yep, we're dividing by a string. pathlib is awesome
resultscsv = data / 'results.csv'
# or
resultscsv = Path(__file__).parent.parent / 'data' / 'results.csv'
# using os
import os.path
thisfile = os.path.abspath(__file__)
programs = os.path.dirname(thisfile)
project1 = os.path.dirname(programs)
data = os.path.join(project1, 'data')
resultscsv = os.path.join(data, 'results.csv')
# or
resultscsv = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'data', 'results.csv')
# or POSSIBLY, but this might not work in all places
resultscsv = os.path.join(__file__, '..', '..', 'data', 'results.csv')
The pathlib approach looks massively more readable to me, and is compounded with the fact that then opening the file becomes:
with resultscsv.open(mode='r') as f:
...
rather than the (slightly) more obtuse
with open(resultscsv, mode='r') as f:
...
Why is python assuming my path is the project root, which is two directory levels up?
According to https://code.visualstudio.com/docs/python/settings-reference :
python.terminal.executeInFileDir
false
Indicates whether to run a file in the file's directory instead of the current folder.
So presumably just set python.terminal.executeInFileDir
to true
.
Getting absolute path when trying to get root directory
cd ../
is change directory command which can be used to go back in directory tree.
example:
If you are in /home/user.com/src/iform/dvops/build_iform_app/src
, then commandcd ../../../../
will change you current working directory to /home/user.com/src/
.
In string notation, if ROOT_DIR
is giving you /home/user.com/src/iform/dvops/build_iform_app/src
, then ROOT_DIR/../../../../
should correspond to /home/user.com/src/
, which you want.
Python - Loading files relative from project root
I like to create some sort of configuration file in the project root that has an aboslute path to the root. I do this only because the frameworks i usually use (django, scrapy) have some sort of convention like this
├ ...
├── pve
│ ├── blahblah
│ │ ├── TestDefinition.py
│ │ ├── TestDefinition.pyc
│ │ ├── __init__.py
│ │ └── __init__.pyc
│ └── pve.py
├── src
│ └── definitions
│ └── THISFILE.yml
└── settings.py
# settings.py
import os
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
DEFINITIONS_ROOT = os.path.join(PROJECT_ROOT, 'src', 'definitions')
from myproject import settings
settings.DEFINITIONS_ROOT
How do I get the parent directory in Python?
Python 3.4Use the pathlib
module.
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent.absolute())
Old answerTry this:
import os
print os.path.abspath(os.path.join(yourpath, os.pardir))
where yourpath
is the path you want the parent for.
Related Topics
Python - Automatically Adjust Width of an Excel File'S Columns
Pandas Merge - How to Avoid Duplicating Columns
How to Find 3 Immediate Words After Keyword Match Using Python
Calculating the Area Under a Curve Given a Set of Coordinates, Without Knowing the Function
Counting the No. of Black to White Pixels in the Image Using Opencv
In Python, How to Split a String and Keep the Separators
Finding the Max Value in a Two Dimensional Array
How to Write List Elements into a Tab-Separated File
Passing Multiple Arguments from Django Template Href Link to View
How to Remove Name and Dtype from Pandas Output
How to Convert Datetime to Integer in Python
How to Clear Your Printed Text in Python
Opening a Word Document That Has a Password Using Docx Library