How to safely create a nested directory in Python

 In order to create a nested directory safely in Python, we could do this:

import os
if not os.path.exists('directory'):
    os.makedirs('directory')

Or after Python 3.5, you could use:

from pathlib import Path
Path("C:/new/new_dir").mkdir(parents=True, exist_ok=True)

If parents=True, the directory new_dir 's parents will be automatically created if they are not existant.  If parents=Flase, it raises FileNotFoundError exception.

The exist_ok paramenter was added in version 3.5,  if it is set to False (default setting), FileExistsError is raised when the file is already present. If it is set to True, FileExistsError will be ignored.


 

Comments

Popular posts from this blog

How to create a memory puzzle game with Python and Pygame (#005)

How to write a slide puzzle game with Python and Pygame (2020 tutorial)

Introduction to multitasking with Python #003 gevent (2020 tutorial)