Categories
Python Answers

How to safely create a nested directory with Python?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *