Reputation: 14685
I have written this:
ancestor_dir = os.path.join(os.path.dirname(__file__), *([os.pardir]*5 + [ancestor_name]))
I'm thinking, why don't I just say
ancestor_dir = os.path.join(os.path.dirname(__file__), "../../../../../", ancestor_name]))
It seems to work in Windows and linux and is a lot easier to understand.
Upvotes: 3
Views: 113
Reputation:
Using ".."
instead of os.pardir
not an issue unless you want to maintain compatibility with the classic Mac OS ( predecessor of OS X ) in which
::
:
:
You can check this by
import macpath
print(macpath.pardir) #print parent dir
print(macpath.curdir) #print current dir
print(macpath.sep) #print dir separator
The os
module imports pardir
from os.path
module.
Importing macpath
imports os.path
of classic Mac OS in other operating systems. Similarly ntpath
is for Windows and posixpath
for POSIX systems.
Using os.pardir
is also useful to maintain readability of the code.
Note: using "../../../../../" is a bad idea in windows because here the directory separator is hard coded too and windows uses "\" as default directory separator (os.sep) . This directory separator is used by os.path.join()
. So the resulting path will look hideous with mixed slashes. There is no compelling reason to stop you from using it and of course mixed slashes can be corrected with os.path.normpath()
Upvotes: 3
Reputation: 24699
Using os.pardir
makes the code portable to non-POSIX systems. If compatibility isn't an issue, then it doesn't matter much. But one could argue that using os.pardir
can be more readable; but that's too subjective to quantify.
Upvotes: 0