Python Language os.path


This module implements some useful functions on pathnames. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings.


  • os.path.join(a, *p)
  • os.path.basename(p)
  • os.path.dirname(p)
  • os.path.split(p)
  • os.path.splitext(p)

Join Paths

To join two or more path components together, firstly import os module of python and then use following:

import os
os.path.join('a', 'b', 'c')

The advantage of using os.path is that it allows code to remain compatible over all operating systems, as this uses the separator appropriate for the platform it's running on.

For example, the result of this command on Windows will be:

>>> os.path.join('a', 'b', 'c')

In an Unix OS:

>>> os.path.join('a', 'b', 'c')

Absolute Path from Relative Path

Use os.path.abspath:

>>> os.getcwd()
>>> os.path.abspath('foo')
>>> os.path.abspath('../foo')
>>> os.path.abspath('/foo')

Path Component Manipulation

To split one component off of the path:

>>> p = os.path.join(os.getcwd(), 'foo.txt')
>>> p
>>> os.path.dirname(p)
>>> os.path.basename(p)
>>> os.path.split(os.getcwd())
('/Users/csaftoiu/tmp', 'foo.txt')
>>> os.path.splitext(os.path.basename(p))
('foo', '.txt')

Get the parent directory

os.path.abspath(os.path.join(PATH_TO_GET_THE_PARENT, os.pardir))

If the given path exists.

to check if the given path exists

path = '/home/john/temp'
#this returns false if path doesn't exist or if the path is a broken symbolic link

to check if the given path is a directory

dirname = '/home/john/python'

to check if the given path is a file

filename = dirname + ''

to check if the given path is symbolic link

symlink = dirname + 'some_sym_link'

to check if the given path is a mount point

mount_path = '/home'