The os.path module

Even with automatic path-separator interpolation, building or hardcoding paths as strings is a messy business. Python's powerful string manipulation methods make it tempting to try to work with paths as strings, and many programmers attempt to do so.

The result is often ugly, non-portable code as follows:

script_dir = '/'.join(some_path.split('/')[:-1])

While this approach might work most of the time (even on Windows), it's prone to breaking on some edge cases (for example, some_path = '/script.sh'). For this reason, the Python standard library includes the  os.path module for working with filesystem paths. We've seen it quite a bit already, but it warrants another look owing to its importance in cross-platform compatibility. ...

Get Python GUI Programming with Tkinter now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.