Python: File Path Manipulation

By Xah Lee. Date: . Last updated: .

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

Get Directory Path

os.path.dirname(path)
Return the dir part of path. (result won't have ending slash, unless it's root dir.)
import os.path

# get dir part of path
print(os.path.dirname("/home/aa/bb.html") == "/home/aa")

Get File Name Part of a Path

os.path.basename(path)
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 Directory Part, File Part

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

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

# split path into dir part, file part
print(os.path.split(fp) == ("/home/aa", "ff.html"))

Get File Extension

os.path.splitext(path)
Split a path into first part and file extension part. Return a Tuple.
import os.path

# python file extension

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

print(xx[0] == "/home/aa/ff")
print(xx[1] == ".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/temp/x20221010.py3"))

Get Relative 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

Absolute Path

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

Python: Paths and Module

Python Text Processing

Python

Overview

Help

Comment

String

Arithmetic

Boolean

Conditional

Loop

Data Structure

Function and Class

Module

Misc

Regex

Text Processing

Web

Misc