Reputation: 17
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')
I am really new to python... May I ask should I understand the codes as follow?
modpath = os.path.dirname(os.path.abspath(sys.argv[0]))
means saving the name of the folder of the current location in absolute path format in the variable modpath? That means not the exact path leading to the current location but its folder?
next,datapath = os.path.join(modpath, '../../datas/orcl-1995-2014.txt')
means saving the join string of the path saved in modpath with the later string?
Upvotes: 0
Views: 4350
Reputation: 6581
os.path.abspath(path)
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
os.path.dirname(path)
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
os.path.join(path1, path2, ...)
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'
sys.argv[0]
- Which is the path to your Python script. Let's say it is /usr/bin/python
.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.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 in
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
.Upvotes: 1
Reputation: 820
os.path.abspath(sys.argv[0]) would return the absolute path. os.path.dirname(path) function returns the head of the path.
modpath would be the head of path.
os.path.join(path1, path2) function would join two directory paths.
Hope this helps!
Upvotes: 0