Sunday, April 20, 2025

Python Try, Except, Finally

Simple if-else blocks will work just fine:


import os

print("Script to check removal of files")
print("-" * 50)

if os.path.exists("deleteme.txt"):
    print("File Detected")
    os.remove("deleteme.txt")
    print("File Removed")
else:
    print("No File There - Nothing To Delete")

Result: 


Script to check removal of files
--------------------------------------------------
File Detected
File Removed
>>> 

If you run script one more time - when there's no file there:


Script to check removal of files
--------------------------------------------------
No File There - Nothing To Delete
>>> 

But more elegant approach is to Try to do something, and if that fails, than we will activate code in Except section.

The best thing here is that code in Finally section will always run.

So, no metter what happens with code in Try/Except, we can always be sure that whatever we put in Finally will get some job done.

It's like backup operation that will always work.


import os

print("Script to check removal of files")
print("-" * 50)

try:
    os.remove("deleteme.txt")
    print("File Removed")
except:
    print("No file - Nothing to Delete")
finally:
    print("This will work - always")

Result: 


Script to check removal of files
--------------------------------------------------
File Removed
This will work - always
>>> 

After second run:


Script to check removal of files
--------------------------------------------------
No file - Nothing to Delete
This will work - always
>>> 

Congratulations - You just finished more than 40 Python Tutorials.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...