I have a working module, I am trying to put toghet a unified yaml file at the ROOT directory, for all sub modules to use.
I have a sub module that is 3 levels deep, and the configs.yaml is at the root.
right now I am accessing the root directory by hardcoding os.path.split()
lines for as many levels as necessay, and I was wondering if there is a more pythonic, or a better more robust way of pointing to directory top.
I am on windows. Python 3.4, using py2exe for building.
The folder structure is as follows .
dps_tools
nydps
winsrv64
and more
if hasattr(sys, 'frozen'):
current_directory = os.path.split(sys.executable)[0]
else:
current_directory = os.path.split(os.path.split(os.path.split(os.path.dirname(
os.path.abspath("__file__")))[0])[0])[0]
if hasattr(sys, 'frozen'):
basis = sys.executable
else:
basis = os.path.dirname(os.path.abspath("__file__"))
current_directory = os.path.split(basis)[0]
Is there a more consistent approach? Or perhaps a oneline pythonic way to access directory top? (even though I am on windows and directory top is not c:)
First, note that os.path.dirname(filepath)
is equivalent to os.path.split(filepath)[0]
.
But if you need to go several levels up, I'd use os.path.normpath(os.path.join(filepath, '..', '..', '..'))
. IMHO it's more readable.
EDIT: ntpath
's normpath
will also replace /
with \\
in the input path, so the line above can be re-written to os.path.normpath(os.path.join(filepath, '../../..'))
, and it's be portable.