Python: File Path Functions

By Xah Lee. Date: . Last updated: .

Here's most frequently used functions for manipulating file/directory path.

Get Directory Path, File Name, File Name Extension

Return the dir part of path. (result does not end in slash, unless it's root dir.)
import os.path

# get dir part of path
print(os.path.dirname("/home/aa/bb.html") == "/home/aa")
Return the file name. Sample return value: "cat.jpg"
import os.path

# get file name part of a path
print(os.path.basename("/home/aa/ff.html") == "ff.html")
Split a path into dir part and file part. Return a Tuple. (note: result of dir part don't have ending slash, unless it's root dir.)
import os.path

xx = "/home/aa/ff.html"

# split path into dir part, file part
print(os.path.split(xx) == ("/home/aa", "ff.html"))
Split a path into first part and file extension part. Return a Tuple.
import os.path

# split extension

xx = os.path.splitext("/home/aa/ff.html")

print(xx == ("/home/aa/ff", ".html"))

Check File Exists

Return True if the file exists, else False.
# check if file exists
import os.path

Relative Path, Absolute Path

os.path.relpath(path, dir)
Return a relative path, of path with respect to dir. (Note: file existance is not checked.)
import os.path

xpath = "/home/aa/bb/ff.html"
xdir = "/home/aa/"

# compute relative path
print(os.path.relpath(xpath, xdir) == "bb\\ff.html")
# on Microsoft Windows
Return a normalized absolutized version of path. Note: it does not resolve symbolic links to its destination.
# get absolute path

import os.path

xx = "/usr/bin/../bin/vi"

# remove redundant ../
# /usr/bin/vi

# similar to os.path.normpath(xx) but does a bit more
# /usr/bin/vi

Real Path of Symbolic Link

Return the canonical path, resolve symbolic links.
# resolve symbolic link

import os.path

# /usr/bin/vim

Python: Paths and Module

Python Text Processing