Python: File Path Manipulation

By Xah Lee. Date: . Last updated: .

This page is a list of the most frequently used functions for manipulating file/directory path.

Get Directory Part, File Name Part, File Extension

Get Directory Path

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

# -*- coding: utf-8 -*-
# python

# get dir part

import os.path

print os.path.dirname("/home/aa/bb/ff.html")
# /home/aa/bb

Get File Name Part of a Path

# -*- coding: utf-8 -*-
# python

# get file name part of a path

import os.path

print os.path.basename("/home/aa/bb/ff.html")
# 'ff.html'

Split Directory Part, File Part

os.path.split("path") → returns a 2-tuple. Split a path into dir part and file part. (note: result of dir part don't have ending slash, unless it's root dir.)

# -*- coding: utf-8 -*-
# python

# split path into dir part, file part

import os.path

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

print os.path.split(fp)
# ('/home/aa/bb', 'ff.html')

print os.path.dirname(fp)
# /home/aa/bb

print os.path.basename(fp)
# ff.html

Note: os.path.split(p) is equal to os.path.dirname(p) + os.path.basename(p)

Get File Extension

os.path.splitext("path") → returns a 2-tuple. Split a path into first part and file extension part.

# -*- coding: utf-8 -*-
# python

# get file extension

import os.path

print os.path.splitext("/home/aa/bb/ff.html")
# ('/home/aa/bb/ff', '.html')

print os.path.splitext("/home/aa/bb/ff.html")[1]
# '.html'

Check File Exists

os.path.exists(path) → Return True if the file exists, else False.

# -*- coding: utf-8 -*-
# python

# check if file exists

import os.path

print os.path.exists("/home/") # True

print os.path.exists("/home/m31455") # False

Get Relative Path

os.path.relpath(path, dir) → returns a relative path, of path with respect to dir. (Note: path existence is not checked.)

# -*- coding: utf-8 -*-
# python

# compute relative path

import os.path

print os.path.relpath("/home/aa/bb/ff.html", "/home/aa/") # bb/ff.html

Absolute Path, Normalized/Cannonical Path

os.path.abspath(path) → Return a normalized absolutized version of path. Note: it does not resolve symbolic links to its destination.

# -*- coding: utf-8 -*-
# python

# get absolute path

import os.path

fp = "/usr/bin/../bin/vi"

# remove redundant ../
print os.path.normpath(fp)
# /usr/bin/vi

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

Real Path, Resolve Symbolic Link

os.path.realpath(path) → Return the canonical path, resolve symbolic links.

# -*- coding: utf-8 -*-
# python

# resolve symbolic link

import os.path

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

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

Python: Paths Topic

  1. File Path Manipulation
  2. Print Version String from Script
  3. Executable Path, Script Path
  4. List Modules, Search Path, Loaded Modules
  5. How to Write a Module

If you have a question, put $5 at patreon and message me.

Python by Example

  1. Python Basics
  2. Print Version String
  3. Builtin Help
  4. Quote String
  5. String Operations
  6. String Methods
  7. Format String
  8. True, False
  9. if then else
  10. for, while, Loops
  11. List Basics
  12. Loop Thru List
  13. Map Function to List
  14. List Comprehension
  15. List Methods
  16. Dictionary
  17. Loop Thru Dict
  18. Dict Methods
  19. Function
  20. Class
  21. List Modules
  22. Write a Module
  23. Unicode 🐍

Regex

  1. Regex Basics
  2. Regex Reference

Text Processing

  1. Read/Write File
  2. Traverse Directory
  3. Manipulate Path
  4. Process Unicode
  5. Convert File Encoding
  6. Find Replace in dir
  7. Find Replace by Regex
  8. Count Word Frequency

Web

  1. Send Email
  2. GET Web Page
  3. Web Crawler
  4. HTTP POST
  5. Check Page Load Size
  6. Thumbnail Generation

Misc

  1. JSON
  2. Find Script Path
  3. Get Env Var
  4. System Call
  5. Decompress Gzip
  6. Complex Numbers

Advanced

  1. Sort
  2. Copy Nested List
  3. Tuple vs List
  4. Sets, Union, Intersection
  5. Closure in Python 2
  6. Decorator
  7. Append String in Loop
  8. Timing f timeit
  9. Keyword Arg Default Value Unstable