Python: File Path Functions

By Xah Lee. Date: . Last updated: .

Get Dir Path, File Name, File Name Extension

os.path.dirname(path)

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")
os.path.basename(path)

Return the file name. e.g. "cat.jpg"

import os.path

# get file name part of a path
print(os.path.basename("/home/aa/ff.html") == "ff.html")
os.path.split(path)

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"))
os.path.splitext(path)

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

os.path.exists(path)

Return True if the file exists, else False.

# check if file exists
import os.path
print(os.path.exists("c:/Users/tt/abc.txt"))

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
os.path.abspath(path)

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 ../
print(os.path.normpath(xx))
# /usr/bin/vi

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

Real Path of Symbolic Link

os.path.realpath(path)

Return the canonical path, resolve symbolic links.

# resolve symbolic link

import os.path

print(os.path.realpath("/usr/bin/vi"))
# /usr/bin/vim

Expand Tilde ~ of User Home Dir

os.path.expanduser(path)

expand the ~ for user home dir.

import os.path

xx = os.path.expanduser("~")
print(xx)
# C:\Users\xah

xx = os.path.expanduser("~/")
print(xx)
# C:\Users\xah/

xx = os.path.expanduser("~/Documents")
print(xx)
# C:\Users\xah/Documents

# tested on Microsoft Windows

Python, Paths and Module

Python, Read Write File