How to Create a Path if it Doesn’t Exist in Python?

Estimated read time 2 min read

To create a path if it doesn’t exist in Python, you can use the os module which provides functions for working with the operating system. Here is an example code that creates a path if it doesn’t exist:

import os

# Define the path to be created
path = 'my/path/to/folder'

# Create the path if it doesn't exist
if not os.path.exists(path):
    os.makedirs(path)

# Check if the path was created
if os.path.exists(path):
    print('Path created:', path)
else:
    print('Failed to create path:', path)

In this code, we first import the os module.

We then define the path to be created as a string 'my/path/to/folder'.

We create the path using the os.makedirs() function which creates all directories in the path recursively. The os.makedirs() function does nothing if the path already exists.

We then check if the path was created using the os.path.exists() function which returns True if the path exists and False otherwise.

Finally, we print a message to the console indicating whether the path was created or not.

After running this code, you should see a message indicating whether the path was created or not. If the path was not created, you may need to check the permissions on the directory or its parent directories.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply