Using Python's os, os.path, and shutil Modules for File and Directory Operations
This article introduces Python's built-in os, os.path, and shutil modules, demonstrating how to create and delete directories, manipulate file paths, list directory contents, and perform advanced file operations such as copying, moving, and compressing files with clear code examples.
In Python programming, handling files and directories is a common task. This tutorial covers three essential modules— os , os.path , and shutil —that provide functions for creating directories, deleting files, processing file paths, and performing more complex file operations.
os module
The os module offers many operating‑system interaction functions, such as creating directories, removing files, and changing the working directory.
Example 1: Get current working directory
import os
# Get current working directory
current_dir = os.getcwd()
print("Current working directory:", current_dir)Example 2: Create a new directory
import os
# Create new directory
new_dir = "my_new_directory"
os.makedirs(new_dir, exist_ok=True)
print(f"Directory '{new_dir}' created.")Example 3: Delete an empty directory
import os
# Delete empty directory
dir_to_delete = "my_new_directory"
os.rmdir(dir_to_delete)
print(f"Directory '{dir_to_delete}' deleted.")Example 4: List directory contents
import os
# List all files and directories in the current directory
for item in os.listdir():
print(item)Example 5: Change the current working directory
import os
# Change current working directory
new_dir = "/path/to/new/directory"
os.chdir(new_dir)
print("Changed working directory to:", os.getcwd())os.path module
The os.path submodule provides utilities for handling file paths, such as checking existence, obtaining file size, and splitting paths.
Example 6: Check if a path exists
import os
# Check if path exists
path = "/path/to/some/file.txt"
if os.path.exists(path):
print(f"The path '{path}' exists.")
else:
print(f"The path '{path}' does not exist.")Example 7: Get file size
import os
# Get file size
file_path = "/path/to/some/file.txt"
size = os.path.getsize(file_path)
print(f"Size of '{file_path}': {size} bytes")Example 8: Split a path
import os
# Split path
path = "/path/to/some/file.txt"
dirname, filename = os.path.split(path)
print("Directory:", dirname)
print("File name:", filename)Example 9: Determine if a path is a file or directory
import os
# Check if path is a file or directory
path = "/path/to/some/file.txt"
if os.path.isfile(path):
print(f"'{path}' is a file.")
elif os.path.isdir(path):
print(f"'{path}' is a directory.")
else:
print(f"'{path}' does not exist or is not a regular file/directory.")shutil module
The shutil module offers higher‑level file operations such as copying, moving, and archiving files and directories.
Example 10: Copy a file
import shutil
# Copy file
src = "/path/to/source/file.txt"
dst = "/path/to/destination/file.txt"
shutil.copy2(src, dst)
print(f"File '{src}' copied to '{dst}'.")Example 11: Move a file
import shutil
# Move file
src = "/path/to/source/file.txt"
dst = "/path/to/destination/file.txt"
shutil.move(src, dst)
print(f"File '{src}' moved to '{dst}'.")Example 12: Compress a folder into a zip archive
import shutil
# Compress folder
folder_to_zip = "/path/to/folder"
archive_name = "/path/to/archive"
shutil.make_archive(archive_name, 'zip', folder_to_zip)
print(f"Folder '{folder_to_zip}' compressed into '{archive_name}.zip'.")Running selected examples demonstrates how to retrieve the current working directory, create a new directory, list directory contents, check path existence, and copy a file, providing a practical overview of common file‑system tasks in Python.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.