Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 988
Sun Bear Avatar asked Jul 29 '19 01:07

Sun Bear


People also ask

Should I use pathlib or os Path?

With Pathlib, you can do all the basic file handling tasks that you did before, and there are some other features that don't exist in the OS module. The key difference is that Pathlib is more intuitive and easy to use. All the useful file handling methods belong to the Path objects.

What is the difference between os mkdir and os Makedirs?

makedirs() creates all the intermediate directories if they don't exist (just like mkdir -p in bash). mkdir() can create a single sub-directory, and will throw an exception if intermediate directories that don't exist are specified. Either can be used to create a single 'leaf' directory (dirA): os.

Why should I use pathlib?

👉 It allows you to iterate on directories and perform pattern matching. Let's assume you have a Path object that points to a directory. Pathlib allows you to easily iterate over that directory's content and also get files and folders that match a specific pattern.

Is pathlib newer than os?

pathlib was introduced in Python 3.4 and offers a different set of abstractions for working with paths. However, just because it is newer, that doesn't mean it's better.


1 Answers

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.

like image 176
Gabriela Melo Avatar answered Oct 18 '22 08:10

Gabriela Melo