os.path
os.path is not one module but two: posixpath on Linux and macOS, ntpath on Windows. Same function names, different rules for separators and drives. Paths are plain strings in, plain strings out — most functions never touch the disk.
import os import os.path from os import path import posixpath, ntpath
Demo
import posixpath p = '/home/ada/report.pdf' (posixpath.dirname(p), posixpath.basename(p), posixpath.splitext(p)[1])
The first two tabs import posixpath directly so they print the same on every computer (on Windows, os.path.join would use '\'). splitext keeps only the last extension — '.gz' for site.tar.gz — and a leading dot is not an extension, so '.bashrc' has none. A trailing slash makes the basename empty: dirname('/var/log/') is '/var/log'. In join, '/etc/passwd' is absolute, so '/srv/app' is discarded; an empty last component adds a trailing separator. The exists tab touches a real (virtual) folder: missing paths give False, never an error.
Members
Common patterns
import os HERE = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join(HERE, 'config.toml')
import os root, ext = os.path.splitext(filename) out = root + '.json'
import os files = [n for n in os.listdir(folder) if os.path.isfile(os.path.join(folder, n))]
import ntpath ntpath.join('C:\\Users', 'ada', 'notes.txt')
Examples
Pitfalls
import posixpath posixpath.join('/srv/uploads', '/etc/passwd')
import posixpath base = '/srv/uploads' p = posixpath.normpath(posixpath.join(base, '/etc/passwd')) posixpath.commonpath([base, p]) == base
folder = 'logs/' folder + '/' + 'app.log'
import posixpath posixpath.join('logs/', 'app.log')
When to use
- Code that already passes str paths around (os.listdir, os.walk results, argv)
- Quick one-off string operations: extension, folder, file name
- New code that does a lot with paths → pathlib.Path has all of this as methods and properties
- URLs → urllib.parse (and posixpath only for the path part)
- Checking before acting (exists then open) → just open and catch FileNotFoundError
Notes
FAQ
Yes — it is ntpath there and posixpath on Linux and macOS. ntpath accepts both \ and /, knows drive letters and UNC shares, and joins with \. To get the same result everywhere, import posixpath or ntpath explicitly.