liveBook · Manning

Os.path.join

As explained in Python Workout, Second Edition

os.path.join is a Python standard-library function that combines path components using the separator conventions of the current operating system.

When a directory name and filename must become a usable path, use os.path.join rather than manually concatenating strings. It accepts multiple components and inserts the directory separator for the current operating system: backslashes on Windows and forward slashes on macOS and Unix/Linux. section 6.15 section 11.15

Build a path from a directory listing

import os for filename in os.listdir('/etc/'): full_path = os.path.join('/etc/', filename) # Open or otherwise process full_path os.listdir returns filenames without the directory name, so joining each result with the directory produces a full pathname. The same strategy applies when iterating through files returned by another listing operation. section 6.17 section 11.15

Keep these distinctions in mind when choosing a path-building approach:

  • Prefer os.path.join to str.join, +, or f-strings when constructing filesystem paths, because it follows the current operating system's separator convention. section 11.15
  • Use glob.glob when a filename pattern should filter results and return complete paths; use pathlib when an object-oriented filesystem API is preferable. section 6.17
filenames = os.listdir('/etc/')

Compare the filenames returned by os.listdir with the directory-qualified paths that os.path.join helps construct. section 6.17

How Python Workout, Second Edition covers it

How deep it goes
Explains multiple arguments and os.sep-based platform handling, while stopping short of detailed filesystem semantics.
Examples
Uses directory listings whose filenames must be combined with a directory to produce complete paths.
What it assumes
Assumes familiarity with filenames, directories, and basic Python function calls; clarifies why listings may need path prefixes.
What you can do after
Apply it via Python's standard library to construct cross-platform paths from directory and filename components.
How it connects
Connects os.listdir, glob.glob, pathlib, str.join, and os.sep as alternative listing, path, or separator mechanisms.

Also explained in

Compare how 3 books explain os.path.join →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.