pythonpython-3.xpathlibos.path

How to switch from Path to os.path and vice versa?


Whenever I want to work with files or directories, the approach of today is to use pathlib. pathlib is great, convenient, easy to use, and OS independent.

However, some libraries still expect me to use os.path. How can I transform my Path to the old-school version?

What should I do with my p in the following example?

from pathlib import Path

p = Path.cwd()
some_old_function(p)   # <---- error

Solution

  • The phrase some libraries still expect me to use os.path seem to confuse you. os.path is a module that simply treats paths as strings - as opposed to pathlib which treats them as specialized objects in the OOP approach.

    To create an easy and well-defined transition between the two representations, PEP 519 was introduced in Python 3.6. It introduces a new abstract class - PathLike - and a new os function - fspath. Any API/library that wishes to implement a path object (pathlib included), should inherit PathLike and implement the __fspath__ method (which will be called by os.fspath).

    The main rationale for this is that using str(path) is error-prone - many objects have a string representation (str(None) gives "None"), but they should not all be treated as paths.

    Specifically for pathlib (at the time of writing this), the implementation of __fspath__ is basically just a wrapper over str(), but you should still arguably prefer to use it in case it ever changes in the future.

    Note that you don't need to actually call os.fspath when passing an argument to most built-in functions. Most os.path functions were changed to accept PathLikes instead of strings and already use os.fspath on it (can be seen in the docs as Changed in version 3.6: Accepts a path-like object. under most functions). So you can simply pass a Path object as-is to most of them.