3

I have below directory structure:

E:\<somepath>\PythonProject
                        -> logs
                        -> configs
                        -> source
                                -> script.py

PythonProject is my main directory and inside the source dir I have some python script. From the script.py I want to access the config file present in configs. Here I don't want to mention the full path like E:\<somepath>\PythonProject\configs\config.json a I will be deploying this to a system for which I am not aware of the path. So I decided to go with

config_file_path = os.path.join(os.path.dirname(file))

But this gives me path to the source dir which is E:\<somepath>\PythonProject\source and I just want E:\<somepath>\PythonProject so that I can later add configs\config.json to access the path to config file.

How can I do this. Thanks

S Andrew
  • 5,592
  • 27
  • 115
  • 237
  • 2
    Does this answer your question? [How do I get the parent directory in Python?](https://stackoverflow.com/questions/2860153/how-do-i-get-the-parent-directory-in-python) – PythonLearner Nov 09 '19 at 11:07

4 Answers4

7

one way:

import os 

config_file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'configs\config.json')

print(config_file_path)

or (you will need to pip install pathlib):

from pathlib import Path

dir = Path(__file__).parents[1]
config_file_path = os.path.join(dir, 'configs/config.json')

print(config_file_path)

third way:

from os.path import dirname as up

dir = up(up(__file__))

config_file_path = os.path.join(dir, 'configs\config.json')
nonamer92
  • 1,887
  • 1
  • 13
  • 24
2

Use pathlib:

from pathlib import Path

p = Path(path_here)

# so much information about the file
print(p.name, p.parent, p.parts[-2])
print(p.resolve())
print(p.stem)

Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57
2

You can do it with just os module:

import os
direct = os.getcwd().replace("source", "config")
mind-protector
  • 248
  • 2
  • 12
2

You can use the pathlib module:

(If you dont have it, use pip install pathlib in Terminal.)

from pathlib import Path
path = Path("/<somepath>/PythonProject/configs/config.json")
print(path.parents[1])

path = Path("/here/your/path/file.txt")
print(path.parent)
print(path.parent.parent)
print(path.parent.parent.parent)
print(path.parent.parent.parent.parent)
print(path.parent.parent.parent.parent.parent)

which gives:

/<somepath>/PythonProject
/here/your/path
/here/your
/here
/
/

(from How do I get the parent directory in Python? by https://stackoverflow.com/users/4172/kender)

  • Why not use a loop? Why not use `parents` that gives all of them? Why reference another question instead of marking this one as a duplicate? – Ofer Sadan Nov 09 '19 at 11:30
  • Thanks @ofer-sadan. I did. I also needed the reputation to reach 15, so my votes count. – Ornataweaver Nov 09 '19 at 11:36