Python pathlib: File Operations Without os.path Concatenation
Pathlib replaced my habit of concatenating paths with os.path.join. Here is how I use it for everyday file operations. I used os.path.join for years to build file paths, string-concatenating segments and hoping the slashes were right. The pathlib module, introduced in Python 3.4, represents paths as objects with methods and operators. Switching to it made my file-handling code shorter, more readable, and cross-platform by default. Building Paths with the Slash Operator A Path object replaces string paths. The slash operator appends path segments, which is cleaner than os.path.join and works identically on Windows and POSIX systems. from pathlib import Path base = Path('/home/user') config = base / 'config' / 'settings.json' # PosixPath('/home/user/config/settings.json') The resulting object is a path, not a string, so it has methods for operations that previously required separate os functions. You can still get the string form with str(path) when a library requires it. Reading and Writing Files Path objects have read_text() , read_bytes() , write_text() , and write_bytes() methods. These handle opening, reading or writing, and closing in one call. For simple operations, they replace the with open(. ) pattern entirely. config_path = Path('settings.json') content…