How can I safely create a nested directory?
Stack How?
Stackorigin – The Community of Question and Answers Latest Articles
Read More About Python List Comprehension with examples
Python List Comprehension: Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list. Advantages of List Comprehension in Python: Time Efficient than loop Space Efficient than loop Needs ...
Do not accept an offer letter from companies.
Do not accept an offer letter from companies without verifying the following points. Designation Salary Details & CTC Distribution Leave Policies Working Hours & Days Medical Coverage/Insurance Probation Period Notice Period Benefits and Perks Bonus F&F Policy
How to call API using Ajax
AJAX stands for Asynchronous JavaScript and XML and its used for to make calls to the server to fetch some data. In this article, we will learn how to implement a simple API call using AJAX technology. How to use GET ...
On Python ≥ 3.5, use
pathlib.Path.mkdir
:For older versions of Python, I see two answers with good qualities, each with a small flaw, so I will give my take on it:
Try
os.path.exists
, and consideros.makedirs
for the creation.Using try except and the right error code from errno module gets rid of the race condition and is cross-platform:
I would personally recommend that you use
os.path.isdir()
to test instead ofos.path.exists()
.Best way to do this in python
Use this command check and create dir
Using os.mkdir()
os.mkdir()
method in Python is used to create a directory named path with the specified numeric mode. This method raiseFileExistsError
if the directory to be created already exists.Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the directory to be created. If this parameter is omitted then default value Oo777 is used.
dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
If the specified path is absolute then dir_fd is ignored.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
Using os.makedirs()
os.makedirs()
method in Python is used to create a directory recursively. That means while making leaf directory if any intermediate-level directory is missing,os.makedirs()
method will create them all.For example, consider the following path:
Suppose we want to create directory ‘Nikhil’ but Directory ‘GeeksForGeeks’ and ‘Authors’ are unavailable in the path. Then
os.makedirs()
method will create all unavailable/missing directories in the specified path. ‘GeeksForGeeks’ and ‘Authors’ will be created first then ‘Nikhil’ directory will be created.Python’s OS module provides a function to create a directory i.e.
Creating nested directories, especially from an absolute path, is precarious because the success of the command relies on the parent directories existing to be nested within.
The
pathlib
library and its.mkdir()
method offer a technique to safely create a nested directory.We begin by importing the
Path
class frompathlib
.from pathlib import Path
When creating the
Path
object, include the directory path to be created.p = Path("/nested/directory")
Next, we’ll use the
.mkdir()
method to create the directory.p.mkdir()
This will work, assuming the directory does not exist.
However, we need a safe mechanism to create the directory without causing exceptions and errors. To do this, let’s add the
exist_ok
flag tomkdir()
so that it does not raise aFileExistsError
if the directory already exists.p.mkdir(exist_ok=True)
What if our directory requires parent directories to be made as well?
Similarly to the
exist_ok
flag, theparents
flag will modify the default behavior, recursively creating directories as necessary.p.mkdir(exists_ok=True, parents=True)
If we want to bundle everything together into a tidy function we can do so as follows:
def makeDirectory(path_to_directory): p = Path(path_to_directory) p.mkdir(exists_ok=True, parents=True)
There are several methods to perform this task, I will discuss a few with you:
If you face an error you can trap and examine it using embedded error code