According to python 3.6 documentation, a directory can be created via:
pathlib.Path.mkdir(mode=0o777, parents=False, exist_ok=False)
os.mkdir(path, mode=0o777, *, dir_fd=None)
os.makedirs(name, mode=0o777, exist_ok=False)
Questions:
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()
?pathlib.Path.mkdir()
vs os.mkdir()
or os.makedirs()
? Any performance differences?Please explain in relation to POSIX considerations. Thanks.
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.
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.
👉 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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With