Skip to content

python mkdir

In Python, you can create a new directory (folder) using the os module or the Path class from the pathlib module. Here are examples using both approaches:

Using the os module:

import os

# Specify the directory path you want to create
new_directory = 'my_new_directory'

# Check if the directory already exists, and if not, create it
if not os.path.exists(new_directory):
    os.mkdir(new_directory)
    print(f"Directory '{new_directory}' created successfully.")
else:
    print(f"Directory '{new_directory}' already exists.")

Using the pathlib module (recommended for Python 3.4 and later):

from pathlib import Path

# Specify the directory path you want to create
new_directory = 'my_new_directory'

# Check if the directory already exists, and if not, create it
path = Path(new_directory)
if not path.exists():
    path.mkdir()
    print(f"Directory '{new_directory}' created successfully.")
else:
    print(f"Directory '{new_directory}' already exists.")

Both of these code snippets will create a new directory called “my_new_directory” in the current working directory if it doesn’t already exist. You can replace 'my_new_directory' with the desired name of the directory you want to create.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)