22

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.

Sun Bear
  • 7,594
  • 11
  • 56
  • 102
  • It seems as if `os.mkdir` is the simplest solution. Given the python philosophy, I suppose the simplest method would be the most preferable. – DarthCadeus Jul 29 '19 at 01:52
  • Difference of `os.mkdir` and `os.makedirs`: [What is different between makedirs and mkdir of os?](https://stackoverflow.com/questions/13819496/what-is-different-between-makedirs-and-mkdir-of-os). – Gino Mempin Jul 29 '19 at 04:23

1 Answers1

17

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.

Gabriela Melo
  • 588
  • 1
  • 4
  • 15
  • 6
    `(Path.mkdir())[https://docs.python.org/3/library/pathlib.html#pathlib.Path.mkdir]` has a parameter called `parents` which is passed `False` by default. If you pass `True`, then any parent of the path is not there those will be created. Usage: `pathObj.mkdir(parents=True, exist_ok=True)` will create the path parts which are not there and if some parts are there then it won't raise the `FileExistsError` exception. – yasouser Aug 03 '19 at 00:53