Introduction
Working with directories is a fundamental part of file management in Python. The os
, shutil
, and pathlib
modules provide a variety of functions and methods to create, delete, list, and navigate directories. This guide covers all the essential directory operations.
Creating Directories
Using os.mkdir()
The os.mkdir()
function creates a single directory.
Syntax
import os
os.mkdir('directory_name')
Example
import os
try:
os.mkdir('example_dir')
print("Directory 'example_dir' created successfully.")
except FileExistsError:
print("Directory 'example_dir' already exists.")
except Exception as e:
print(f"An error occurred: {e}")
Using os.makedirs()
The os.makedirs()
function creates directories recursively.
Syntax
import os
os.makedirs('parent_dir/child_dir')
Example
import os
try:
os.makedirs('parent_dir/child_dir')
print("Nested directories 'parent_dir/child_dir' created successfully.")
except FileExistsError:
print("Directory 'parent_dir/child_dir' already exists.")
except Exception as e:
print(f"An error occurred: {e}")
Using pathlib.Path.mkdir()
The pathlib
module provides an object-oriented approach to creating directories.
Example
from pathlib import Path
path = Path('example_dir')
try:
path.mkdir()
print("Directory 'example_dir' created successfully.")
except FileExistsError:
print("Directory 'example_dir' already exists.")
except Exception as e:
print(f"An error occurred: {e}")
Creating Nested Directories
from pathlib import Path
path = Path('parent_dir/child_dir')
try:
path.mkdir(parents=True, exist_ok=True)
print("Nested directories 'parent_dir/child_dir' created successfully.")
except Exception as e:
print(f"An error occurred: {e}")
Deleting Directories
Using os.rmdir()
The os.rmdir()
function deletes an empty directory.
Example
import os
try:
os.rmdir('example_dir')
print("Directory 'example_dir' deleted successfully.")
except FileNotFoundError:
print("The directory 'example_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except OSError as e:
print(f"Error: {e}")
Using shutil.rmtree()
The shutil.rmtree()
function deletes a directory and all its contents.
Example
import shutil
try:
shutil.rmtree('parent_dir')
print("Directory 'parent_dir' and all its contents deleted successfully.")
except FileNotFoundError:
print("The directory 'parent_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Using pathlib.Path.rmdir()
The pathlib.Path.rmdir()
method deletes an empty directory.
Example
from pathlib import Path
path = Path('example_dir')
try:
path.rmdir()
print("Directory 'example_dir' deleted successfully.")
except FileNotFoundError:
print("The directory 'example_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except OSError as e:
print(f"Error: {e}")
Deleting Non-Empty Directories
For non-empty directories, use shutil
with pathlib
.
from pathlib import Path
import shutil
path = Path('parent_dir')
try:
shutil.rmtree(path)
print("Directory 'parent_dir' and all its contents deleted successfully.")
except FileNotFoundError:
print("The directory 'parent_dir' does not exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An error occurred: {e}")
Listing Directories
Using os.listdir()
The os.listdir()
function returns a list of entries in the directory.
Example
import os
files = os.listdir('.')
print(files)
Filtering Files
files = [f for f in os.listdir('.') if os.path.isfile(os.path.join('.', f))]
print(files)
Using os.walk()
The os.walk()
function generates the file names in a directory tree.
Example
import os
for root, dirs, files in os.walk('.'):
for name in files:
print(os.path.join(root, name))
Using glob.glob()
The glob
module finds pathnames matching a pattern.
Example
import glob
txt_files = glob.glob('*.txt')
print(txt_files)
Recursive Listing
txt_files = glob.glob('**/*.txt', recursive=True)
print(txt_files)
Using pathlib.Path.iterdir()
The pathlib
module provides an easy way to list directory contents.
Example
from pathlib import Path
path = Path('.')
files = [f for f in path.iterdir() if f.is_file()]
print(files)
Filtering by Extension
txt_files = list(Path('.').glob('*.txt'))
print(txt_files)
Recursive Listing
txt_files = list(Path('.').rglob('*.txt'))
print(txt_files)
Navigating Directories
Using os.chdir()
The os.chdir()
function changes the current working directory.
Example
import os
os.chdir('example_dir')
print("Current working directory:", os.getcwd())
Using pathlib.Path.cwd()
The pathlib.Path.cwd()
method gets the current working directory.
Example
from pathlib import Path
print("Current working directory:", Path.cwd())
Conclusion
Working with directories in Python is straightforward with the help of the os
, shutil
, and pathlib
modules. These modules provide a variety of functions and methods to create, delete, list, and navigate directories efficiently. Understanding these operations is essential for effective file and directory management in Python applications.