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


