16
Lesson 16
Working with directories
Objective
By the end of this lesson, students will understand how to create, remove, and navigate directories in Python. They will learn to use the 'os' module and the 'pathlib' module for effective directory management.
1. Introduction to directories:
Directories, also known as folders, are a way to organize files on your computer. Managing directories is essential for keeping your file system structured and efficient.
2. Creating directories with os.mkdir() and os.makedirs();
The os.mkdir() function allows you to create a single directory, while os.makedirs() can create intermediate directories if they don’t exist.
By the end of this lesson, students will understand how to create, remove, and navigate directories in Python. They will learn to use the 'os' module and the 'pathlib' module for effective directory management.
1. Introduction to directories:
Directories, also known as folders, are a way to organize files on your computer. Managing directories is essential for keeping your file system structured and efficient.
2. Creating directories with os.mkdir() and os.makedirs();
The os.mkdir() function allows you to create a single directory, while os.makedirs() can create intermediate directories if they don’t exist.
import os # Creating a single directory os.mkdir("new_directory") print("Created directory 'new_directory'.") # Creating nested directories os.makedirs("parent_directory/child_directory") print("Created nested directories 'parent_directory/child_directory'.")
3. Removing directories with os.rmdir() and os.removedirs():
To remove directories, you can use os.rmdir() for an empty directory and os.removedirs() for removing nested directories.
import os # Removing an empty directory os.rmdir("new_directory") print("Removed directory 'new_directory'.") # Removing nested directories os.removedirs("parent_directory/child_directory") print("Removed nested directories 'parent_directory/child_directory'.")
Note: os.removedirs() will remove the entire directory tree if it is empty.
4. Navigating directories:
To navigate directories, you can use os.chdir() to change the current working directory and os.getcwd() to get the current working directory.
import os # Changing the current working directory os.chdir("parent_directory") print(f"Current directory changed to: {os.getcwd()}")
5. Using pathlib for directory management:
The pathlib module offers a more object-oriented approach to handling directories and files.
Creating Directories with pathlib:
from pathlib import Path # Creating a directory Path("new_directory").mkdir(exist_ok=True) # exist_ok=True prevents an error if it already exists print("Created directory 'new_directory' using pathlib.")
Removing Directories with pathlib:
# Removing a directory Path("new_directory").rmdir() # This only works if the directory is empty print("Removed directory 'new_directory' using pathlib.")
6. Listing directory contents with os.listdir() and pathlib.Path.iterdir():
You can list the contents of a directory using os.listdir() or pathlib.Path.iterdir().
Example with os:
import os # Listing contents of a directory contents = os.listdir("parent_directory") print("Contents of 'parent_directory':", contents)
Example with pathlib:
from pathlib import Path # Listing contents using pathlib for item in Path("parent_directory").iterdir(): print(item)
7. Checking Directory existence with os.path.exists() and pathlib.Path.exists():
To check if a directory exists, you can use os.path.exists() or pathlib.Path.exists().
Example with 'os':
if os.path.exists("parent_directory"): print("Directory 'parent_directory' exists.") else: print("Directory 'parent_directory' does not exist.")
Example with 'pathlib':
if Path("parent_directory").exists(): print("Directory 'parent_directory' exists using pathlib.")
8. Best Practices:
- Use context managers: Whenever possible, use context managers to manage resources efficiently.
- Check before deleting: Always check if a directory is empty or exists before attempting to remove it.
- Organize files: Regularly organize files into directories to improve file management and accessibility.
9. Practical use cases:
- Project organization: Create directories for different projects to keep files separated and organized.
- Temporary files: Create a temporary directory for storing temporary files during processing.
- Backup management: Create directories for backups to ensure data is preserved.
10. Exercises:
Exercise 1: Creating directories
1. Write a script that creates a directory named 'test_directory' and a nested directory named 'test_directory/nested_directory'.
Exercise 2: Removing directories
1. Write a program that removes an empty directory named empty_directory.
Exercise 3: Navigating directories
1. Change the current working directory to a directory of your choice and print the current working directory.
Exercise 4: Listing directory contents
1. Write a script that lists all files and directories in the current directory.
Exercise 5: Checking directory existence
1. Create a function that checks if a directory exists and prints a message indicating whether it exists.
Conclusion
In this lesson, students learned how to create, remove, and navigate directories in Python using the 'os' and 'pathlib' modules. They explored best practices for directory management, equipping them with essential skills for organizing and handling files in their applications.