Menu Close

How to safely create a nested directory with Python?

Sometimes, we want to safely create a nested directory with Python

In this article, we’ll look at how to safely create a nested directory with Python.

How to safely create a nested directory with Python?

To safely create a nested directory with Python, we can use the patlib
s mkdir method.

For instance, we write

from pathlib import Path
Path("/foo/bar").mkdir(parents=True, exist_ok=True)

to create a directory in the /foo/bar/ folder by calling mkdir with the parents set to True to create the directory when the parent folder exists.

exist_ok is set to True makes mkdir ignore existing files if they have the same name as the path.

Conclusion

To safely create a nested directory with Python, we can use the patlib
s mkdir method.

Posted in Python, Python Answers