How to Safely Create a Directory in Python, Only if It Does Not Exist?

python

To create a directory in Python, you will need to import the os module and use the os.makedirs() method. To ensure that the directory only gets created if it does not exist, you will need to use a conditional statement.

Here's an example code snippet that creates a directory called "my_directory" in the current working directory, but only if it doesn't already exist:

import os

directory = "my_directory"

if not os.path.exists(directory):
    os.makedirs(directory)
    print("Directory created successfully!")
else:
    print("Directory already exists!")

In this code, we first define the name of the directory we want to create. Then, we use the os.path.exists() method to check if the directory already exists. If it does not exist, we use the os.makedirs() method to create the directory and print a success message. If it does exist, we print a message indicating that the directory already exists.

By using this code, you can safely create a directory in Python without overwriting any existing directories.

Latest Questions

python How to Fix ""zsh: command not found: python" Error on MacOS X? python How to Fix "xlrd.biffh.XLRDError: Excel xlsx file; not supported" Error in Pandas? python How to Remove All Whitespace From a Python String?