os.path is Python’s standard-library interface for manipulating filesystem pathnames without writing operating-system-specific syntax. Importing os makes os.path available; paths remain strings, but path construction and inspection use dedicated functions. section 12.2.4
Use os.path.join to combine directory names, filenames, or existing subpaths. It selects the separator expected by the underlying operating system, making it the fundamental portable way to build relative paths. section 12.2.4
Common path operations include:
- os.path.split separates a path into its directory portion and final component. section 12.2.4
- os.path.basename returns the final filename or directory name. section 12.2.4
- os.path.dirname returns the directory portion. section 12.2.4
- os.path.splitext separates a pathname from its extension, while os.path.expandvars substitutes environment variables. section 12.2.4
import os
print(os.path.join('bin', 'utils', 'disktools'))
bin/utils/disktools
Joining 'bin', 'utils', and 'disktools' produces a platform-appropriate path such as bin/utils/disktools. section 12.2.4
Build and inspect a path
import os path = os.path.join('some', 'directory', 'path.jpg') print(os.path.basename(path)) # path.jpg print(os.path.dirname(path)) # some/directory print(os.path.splitext(path)) # ('some/directory/path', '.jpg') section 12.2.4
For filesystem tasks, os.path can support calculations over selected files and operations such as moving matching files into a backup directory. pathlib offers an alternative approach to the same kinds of tasks. section 12.6
