When a directory and filename arrive separately, combine them with os.path.join rather than manually adding separators. It joins path components using the current operating system’s conventions. section 5.17 section 10.12
Use it when working with filenames returned by directory operations:
- os.listdir returns filenames without their directory, so combine each filename with the original path before opening or processing it. section 10.12
- Pass any number of path components; the function joins them with os.sep, selecting forward or backward slashes as appropriate. section 10.12
Build complete paths from directory entries
import os path = '/etc/' for filename in os.listdir(path): full_path = os.path.join(path, filename) print(full_path) This avoids choosing a separator manually and produces a path suitable for subsequent file operations. section 10.12
filenames = os.listdir('/etc/')
Inspect the filename-only result that makes joining the directory path necessary. section 5.20


