Practical 9: Python program that creates a new directory and changes the current working directory to that newly created directory.
Problem Statement
Write a Python program that creates a new directory and changes the current working directory to that newly created directory.
Solution Code
import os
# Function to create and change directory
def create_and_change_directory(new_dir):
try:
# Get current working directory
current_dir = os.getcwd()
print(f"Current Directory: {current_dir}")
# Check if the directory already exists
if not os.path.exists(new_dir):
os.mkdir(new_dir) # Create new directory
print(f"Directory '{new_dir}' created successfully.")
else:
print(f"Directory '{new_dir}' already exists.")
# Change to the new directory
os.chdir(new_dir)
print(f"Changed to new directory: {os.getcwd()}")
except Exception as e:
print(f"An error occurred: {e}")
# Call the function with a directory name
create_and_change_directory("NewFolder")
Output
When the program is executed, it should:
- Display the current working directory.
- Create a new directory named “NewFolder” (if it doesn’t already exist).
- Change the working directory to “NewFolder”.
- Print the updated working directory.
Example Output
Directory 'NewFolder' created successfully.
Changed to new directory: D:\python\NewFolder
Process finished with exit code 0
If the directory already exists:
Directory 'NewFolder' already exists.
Changed to new directory: D:\python\NewFolder
Process finished with exit code 0
Explanation
Below is the explanation of F.E. PPS Unit 4 Practical 9 solution where we have written Python program that creates a new directory and changes the current working directory to that newly created directory.
- Getting the Current Directory (os.getcwd())
- The program first prints the current working directory before making changes.
- Creating a New Directory (os.mkdir())
- os.mkdir(new_dir) creates a new folder if it does not already exist.
- os.path.exists(new_dir) checks whether the folder exists to prevent errors.
- Changing the Working Directory (os.chdir())
- os.chdir(new_dir) sets the new directory as the current working directory.
- os.getcwd() is used to confirm the change.
- Error Handling
- If an error occurs (e.g., permission issues), the program catches the exception and displays an error message.
Key Concepts Learned
- File and Directory Handling (os module)
- os.getcwd() → Gets the current working directory.
- os.mkdir() → Creates a new directory.
- os.path.exists() → Checks if a directory exists.
- os.chdir() → Changes the working directory.
- Exception Handling (try-except)
- The program prevents crashes by handling unexpected errors (e.g., lack of permissions).