Python os.path module

Common Usage of os.path module

This article records some very common usages of os.path module in Python.

Since there are few examples in the docs of os.path module, I added examples for all part in this article.

os.path.expanduser()

Expand ~ and ~user constructions. If user or $HOME is unknown, do nothing.

1
2
3
4
5
6
7
path = "~/file.txt"
full_path = os.path.expanduser(path)
# return: '/Users/shuo/file.txt'

os.environ["HOME"] = "/home / GeeksForGeeks"
full_path = os.path.expanduser(path)
# return: '/home / GeeksForGeeks/file.txt'

os.path.join()

Join one or more path components intelligently.

1
2
3
4
>>> os.path.join('a','b','c')
'a/b/c'
>>> os.path.join('a','b','c','')
'a/b/c/'

os.path.split()

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that.

  • The tail part will never contain a slash;
    • if path ends in a slash, tail will be empty.
    • If there is no slash in path, head will be empty.
    • If path is empty, both head and tail are empty.
      1
      2
      3
      4
      5
      6
      7
      >>> test_s="/home/sa2y18/mydocuments"
      >>> os.path.split(test_s)
      ('/home/sa2y18', 'mydocuments')

      >>> test_s=test_s+'/'
      >>> os.path.split(test_s)
      ('/home/sa2y18/mydocuments', '')

Reference

  1. https://docs.python.org/2/library/os.path.html
  2. my gist