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.
-
Arguably, the [os.pardir]*5 is easier to read than counting five "../" in terms of knowing how far up it went ... but that doesn't seem very persuasive: subjective at best. I'm looking for a more concrete "absolute" reason.GreenAsJade– GreenAsJade2016年05月28日 00:46:08 +00:00Commented May 28, 2016 at 0:46
-
Are you bothered about Windows compatibility? If you know that you will only ever run on Linux or OSX then carry on using the UNIX representation.Salim Fadhley– Salim Fadhley2016年05月28日 12:06:04 +00:00Commented May 28, 2016 at 12:06
-
@SalimFadhley as I said in the question, '../..' appears to work in python under Windows.GreenAsJade– GreenAsJade2016年05月29日 08:26:55 +00:00Commented May 29, 2016 at 8:26
2 Answers 2
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
- Parent directory is denoted by
:: - Directory separator is denoted by
: - Current directory is also denoted by
:
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()
Comments
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.
3 Comments
` instead of /. POSIX are *nix systems, basically. If a system is non-POSIX, there's no guarantee that ../` represents the parent directory. So if this is for a project you want to run on literally anything, avoid using literal paths.