Directory handling is a crucial aspect of file system management in Python. It allows developers to create, navigate, and manipulate directories efficiently. The os
module provides powerful tools for these operations.
To create a new directory, use the os.mkdir()
function. For nested directories, employ os.makedirs()
.
import os
# Create a single directory
os.mkdir("new_folder")
# Create nested directories
os.makedirs("parent/child/grandchild")
The os.listdir()
function returns a list of entries in a specified directory. For more detailed information, use os.scandir()
.
# List directory contents
print(os.listdir("."))
# Detailed directory scan
with os.scandir(".") as entries:
for entry in entries:
print(entry.name, "- Directory" if entry.is_dir() else "- File")
Navigate between directories using os.chdir()
. This function changes the current working directory.
# Change directory
os.chdir("/path/to/new/directory")
# Print current working directory
print(os.getcwd())
To delete an empty directory, use os.rmdir()
. For removing directories with contents, utilize shutil.rmtree()
from the shutil
module.
import shutil
# Remove empty directory
os.rmdir("empty_folder")
# Remove directory and its contents
shutil.rmtree("non_empty_folder")
shutil.rmtree()
.To enhance your understanding of Python file system operations, explore these related topics:
Mastering directory handling in Python is essential for efficient file system management and automation tasks. Practice these techniques to improve your skills in manipulating directories and files programmatically.