In this tutorial, we will be exploring how you can easily create a new directory within the current working directory using Python.
Operating a file system with Python is a common task and could significantly speed up your workflow. In Python, the os module provides several functions to interact with the file system, including creating new directories. Let’s dive in and get started!
Step 1: Import Necessary Module
The first step you need to take is to import the os module in your Python script. This module provides a portable way for using operating system-dependent functions.
1 |
import os |
Step 2: Define Directory Name
Now that we have the necessary module, you need to specify the name of the directory that you want to create. For instance:
1 |
dir_name = "new_directory" |
Step 3: Get the Current Working Directory
The os module has a method called getcwd() that returns the current working directory. We’ll use this method to find out where our new directory will be created.
1 |
current_directory = os.getcwd() |
Step 4: Generate the Full Path
Next, we concatenate the current directory path with our new directory name to generate the full path of our new directory.
1 |
new_dir_path = os.path.join(current_directory, dir_name) |
Step 5: Create the New Directory
Finally, we use the mkdir() function from the os module to create a directory at the specified path. Make sure to wrap our function call in a try block to account for any errors that might occur, like if the directory already exists.
1 2 3 4 5 |
try: os.mkdir(new_dir_path) print("Directory '%s' created" % dir_name) except FileExistsError: print("Directory '%s' already exists" % dir_name) |
Below is the Full Python Code:
1 2 3 4 5 6 7 8 9 10 11 |
import os dir_name = "new_directory" current_directory = os.getcwd() new_dir_path = os.path.join(current_directory, dir_name) try: os.mkdir(new_dir_path) print("Directory '%s' created" % dir_name) except FileExistsError: print("Directory '%s' already exists" % dir_name) |
Output:
Directory 'new_directory' created
Conclusion
By successfully following these steps, you’ve learned how to create a new directory at your current working directory using Python. This feature is extremely useful when it comes to handling files, as it allows you to automate or simplify creating folders in your system when necessary. Keep practicing to be more proficient in these tasks!