Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the Python submodule os.path

Comments

  1. It is suggested that you use use pathlib package instead of os.path.
In [1]:
import os
import inspect

abspath

https://docs.python.org/3/library/os.path.html#os.path.abspath

Return a normalized absolutized version of the pathname path. Notice that a path that is a symbolic link is not automatically traced to the original path. You have to use the function os.path.realpath to get the original path of a file. Notice that os.path.realpath calls os.path.abspath internally so that you do not need to call os.path.abspath by yourself when you use os.path.realpath.

In [3]:
os.path.abspath("path.ipynb")
Out[3]:
'/workdir/learning/0-programming/1-python/3-file_system/os/path.ipynb'
In [5]:
print(inspect.getsource(os.path.abspath))
def abspath(path):
    """Return an absolute path."""
    path = os.fspath(path)
    if not isabs(path):
        if isinstance(path, bytes):
            cwd = os.getcwdb()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)

dirname

In [13]:
path.dirname(path.abspath("path.ipynb"))
Out[13]:
'/jupyter/learning/python/file_system'

basename

In [4]:
path.basename(path.abspath("path.ipynb"))
Out[4]:
'path.ipynb'
In [6]:
path.basename("path.ipynb")
Out[6]:
'path.ipynb'

os.path.pardir

os.path.pardir is not a directory but instead a str object '..'.

In [11]:
os.path.realpath(os.path.join("/home/dclong", os.path.pardir))
Out[11]:
'/home'

The parent directory of / is itself.

In [13]:
os.path.realpath(os.path.join("/", os.path.pardir))
Out[13]:
'/'

isdir

In [6]:
path.isdir("/home/dclong")
Out[6]:
True

isfile

Returns True on

1. file
2. symbolic link to file

Returns False on

1. directory
2. symbolic link to directory
In [4]:
import os

# /home/chud is a directory
os.path.isfile("/home/dclong")
Out[4]:
False
In [2]:
import os

# test.dat is a symbolic link to test.txt
os.path.isfile("test.dat")
Out[2]:
True

exists

In [8]:
path.exists("/home/dclong")
Out[8]:
True
In [9]:
%ls
path.ipynb*
In [3]:
dir(path)
Out[3]:
['__all__',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_get_sep',
 '_joinrealpath',
 '_varprog',
 '_varprogb',
 'abspath',
 'altsep',
 'basename',
 'commonpath',
 'commonprefix',
 'curdir',
 'defpath',
 'devnull',
 'dirname',
 'exists',
 'expanduser',
 'expandvars',
 'extsep',
 'genericpath',
 'getatime',
 'getctime',
 'getmtime',
 'getsize',
 'isabs',
 'isdir',
 'isfile',
 'islink',
 'ismount',
 'join',
 'lexists',
 'normcase',
 'normpath',
 'os',
 'pardir',
 'pathsep',
 'realpath',
 'relpath',
 'samefile',
 'sameopenfile',
 'samestat',
 'sep',
 'split',
 'splitdrive',
 'splitext',
 'stat',
 'supports_unicode_filenames',
 'sys']

expanduser

In [2]:
os.path.expanduser("~")
Out[2]:
'/Users/dclong'

os.path.realpath(path)

os.path.realpath returns the canonical path of the specified filename, eliminating any symbolic links encountered in the path.

Notice that os.path.realpath calls os.path.abspath so that you do not have to call os.path.abspath by yourself when you call os.path.realpath.

In [6]:
print(inspect.getsource(os.path.realpath))
def realpath(filename):
    """Return the canonical path of the specified filename, eliminating any
symbolic links encountered in the path."""
    filename = os.fspath(filename)
    path, ok = _joinrealpath(filename[:0], filename, {})
    return abspath(path)

os.path.splitext

In [1]:
import os

os.path.splitext("abc.txt")
Out[1]:
('abc', '.txt')
In [2]:
import os

os.path.splitext("ab")
Out[2]:
('ab', '')
In [2]:
arr = [0, 1]
In [3]:
o, v = arr
In [4]:
o
Out[4]:
0
In [5]:
v
Out[5]:
1
In [6]:
arr = [[0, 1], [0, 3]]
In [7]:
for o, v in arr:
    print(str(o) + ": " + str(v))
0: 1
0: 3

os.path.normpath

Strips the trailing forward slash from a path.

In [1]:
import os

os.path.normpath("./")
Out[1]:
'.'
In [9]:
os.path.normpath("/some/path/")
Out[9]:
'/some/path'
In [10]:
os.path.normpath("/some/path")
Out[10]:
'/some/path'
In [7]:
os.path.basename("/some/path")
Out[7]:
'path'
In [8]:
os.path.basename("/some/path/")
Out[8]:
''

Comments