Search⌘ K
AI Features

os.path and related functions

Explore how to use the os.path sub-module functions to manipulate file paths and directories in Python. Understand methods such as basename, dirname, exists, isfile, isdir, join, and split to handle and verify file system paths efficiently.

os.path

The os.path sub-module of the os module has lots of great functionality built into it. We’ll be looking at the following functions:

  • basename
  • dirname
  • exists
  • isdir and isfile
  • join
  • split

There are lots of other functions in this sub-module. You are welcome to go read about them in the Python documentation, section 10.1.

os.path.basename

The basename function will return just the filename of a path. Here is an example:

Python 3.5
import os
print(os.path.basename(r'/usercode/test.txt'))
# 'test.txt'

I have found this useful whenever I need to use a filename for naming some related file, such as a log file. This happens a lot when I’m processing a data file.

os.path.dirname

The dirname ...