First, let's understand what each function do:
Return a normalized absolutized version of the pathname path.
You used:
os.path.abspath(sys.argv[0])
Example:
>>> print(os.path.abspath(sys.argv[0])) /usr/bin/ipython
Pathlib equivalent:
>>> pathlib.Path(sys.argv[0]).resolve() /usr/bin/ipython
Returns the directory name of path.
You used:
os.path.dirname(os.path.abspath(sys.argv[0]))
Example:
>>> os.path.dirname('/usr/bin/ipython') /usr/bin
Pathlib equivalent:
import pathlib path = pathlib.Path(sys.argv[0]) modpath = path.parent
Joins one or more path components.
You used:
os.path.join(modpath, '../../datas/orcl-1995-2014.txt')
Example:
>>> print(os.path.join('/etc', 'dir1', '..', 'dir2', 'dir3/dir4')) /etc/dir1/../dir2/dir3/dir4
Pathlib equivalent:
datapath = modpath.parent.parent / 'datas' / 'orcl-1995-2014.txt'
Now, let's follow the code:
- Resolve
sys.argv[0] - Which is the path to your Python script. Let's say it is /usr/bin/python. - Apply
os.path.abspath on /usr/bin/python - You can try it in the interpreter. The result is /usr/bin/python, since it is already an absolute path. - Apply
os.path.dirname on the result (/usr/bin/python). The result is the directory name of usr/bin/python', which is/usr/bin. Save it inmodpath`. - Concatenate modpath (
/usr/bin/) with ../../datas/orcl-1995-2014.txt using os.path.join - which results in /usr/bin/../../datas/orcl-1995-2014.txt. Save it on datapath.
../../datas blah blhasys.argv[0]is the name of the script, not the current working directory. If the script is in the current directory then of course they are the same, but if you runpython ../script.pythen the result is the parent directory of the current directory, and if you runpython /path/to/script.pythen the result is/path/towhich may or may not be entirely different from the current working directory.