Search code examples
pythondirectorysubdirectorypathlib

When should I use pathlib.Path.mkdir() vs os.mkdir() or os.makedirs()?


According to python 3.6 documentation, a directory can be created via:

  1. pathlib.Path.mkdir(mode=0o777, parents=False, exist_ok=False)
  2. os.mkdir(path, mode=0o777, *, dir_fd=None)
  3. os.makedirs(name, mode=0o777, exist_ok=False)

Questions:

  1. It looks like pathlib.Path.mkdir() does most of what os.mkdir() and os.makedirs() do. Is pathlib.Path.mkdir() a "modern" implementation of both os.mkdir() and os.makedirs()?
  2. When should I use pathlib.Path.mkdir() vs os.mkdir() or os.makedirs()? Any performance differences?

Please explain in relation to POSIX considerations. Thanks.


Solution

  • mkdir does not create intermediate-level directories that are not existent at the time of function calling. makedirs does.

    Path.mkdir also does, but it's called as a method of a Path object (whereas the other two are called receiving the path, be it by a string with the path or a Path object (starting on Python 3.6), as an argument to the function).

    Otherwise, behavior is the same.