Tsz Chun Leung
Tsz Chun Leung

Reputation: 17

os.path.dirname and os.path.join

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

Answers (2)

Yam Mesicka
Yam Mesicka

Reputation: 6581

First, let's understand what each function do:

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'

Now, let's follow the code:

  1. Resolve sys.argv[0] - Which is the path to your Python script. Let's say it is /usr/bin/python.
  2. 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.
  3. 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`.
  4. 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.

Upvotes: 1

Bharat Gera
Bharat Gera

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

Related Questions