What is the safest way to create a directory in Python, including intermediate directories?

I’m trying to create a directory in my Python script using the os module, but I want to make sure that any intermediate directories are created as well if they don’t already exist. How can I do this safely?

Here’s the code I have so far:

import os

directory = '/path/to/new/directory'

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

This seems to work, but I’m not sure if it’s the best way to do this. Are there any potential issues with this approach? And are there any better or more efficient ways to create a directory with intermediate directories in Python?

Any help or suggestions would be greatly appreciated. Thank you!