In a previous post, I showed how to add logging to a Python automation script so we can see what it’s doing while it runs.
Logging improves visibility — but it doesn’t prevent failures.
If something goes wrong, the script can still crash.
In this post, I’ll show how to add basic error handling to a Python automation script so it fails gracefully and gives useful information when problems occur.
Why Error Handling Matters
In automation and DevOps workflows, scripts often:
- Run unattended
- Execute on schedules
- Operate on files and systems that can change
Without error handling:
- One small issue can crash the entire script
- You may not know why it failed
- Automation becomes unreliable
Error handling helps you:
- Prevent unexpected crashes
- Capture useful error information
- Make scripts safer to run automatically
Common Errors in File Automation
For our file-organizing script, common issues include:
- Missing directories
- Permission errors
- Files being used by another process
- Unexpected file formats
These are normal — and predictable.
Using Try / Except in Python
Python provides try and except blocks to handle errors safely.
Basic structure:
try: # code that might failexcept Exception as e: # code that runs if an error occurs
This allows the script to continue running instead of crashing.
Adding Error Handling to the Script
Here’s the updated version of the file organizer script with logging + error handling:
import osimport shutilimport logginglogging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")source_folder = "files"for filename in os.listdir(source_folder): file_path = os.path.join(source_folder, filename) try: if os.path.isfile(file_path): extension = filename.split(".")[-1] folder_name = extension.upper() + "_files" folder_path = os.path.join(source_folder, folder_name) os.makedirs(folder_path, exist_ok=True) shutil.move(file_path, folder_path) logging.info(f"Moved {filename} to {folder_name}") except Exception as error: logging.error(f"Failed to process {filename}: {error}")
What Changed
- Wrapped file operations in a
tryblock - Caught errors using
except - Logged failures instead of crashing
- Allowed the script to continue processing other files
Now, one bad file won’t stop the entire automation.
Why This Is a DevOps-Style Improvement
This change:
- Makes the script fault-tolerant
- Improves reliability
- Enables safe unattended execution
- Aligns with production automation practices
Logging + error handling is the minimum standard for real automation.
What’s Next
In the upcoming posts, I plan to:
- Make the script configurable using arguments
- Run it automatically using cron
- Explore running it as a background task
This is how small scripts evolve into real tools.
Conclusion
Error handling turns a fragile script into a reliable automation tool.
Combined with logging, it ensures your script:
- Fails safely
- Provides useful feedback
- Is ready for real-world usage
This is a key step toward production-ready automation.
Leave a comment