Python Finally Block

PythonPythonBeginner
Practice Now

Introduction

In the ancient Egyptian Pharaoh's palace, a scene of mystical allure and complex hieroglyphics unfolds. The Queen of Egypt, with her profound wisdom, has encountered a critical challenge: the sacred scripts used to maintain the balance of the Nile's flooding are at risk of being lost forever. You, as a trusted sage, have been summoned to the palace to construct a resilient system that ensures the preservation of these scripts, using the powers of Python's finally block.

Your goal is to craft an unbreakable transcript-keeper that will perform its duties even when faced with unforeseen errors. Using your skills, you will guide the construction of Python scripts that handle exceptions and guaranteed actions through the finally block, ensuring that the Queen's sacred scripts will endure through any trial or tribulation.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ErrorandExceptionHandlingGroup(["`Error and Exception Handling`"]) python/ErrorandExceptionHandlingGroup -.-> python/finally_block("`Finally Block`") subgraph Lab Skills python/finally_block -.-> lab-271554{{"`Python Finally Block`"}} end

Constructing the Temple of Try-Except-Finally

In this step, you will build the foundation of your transcript-keeper by creating a Python file that will withstand any potential failures during its execution. You will utilize the Python try, except, and finally blocks to accomplish this.

Open a file named transcript_keeper.py in ~/project. In this file, write a Python script that attempts to read an important script from a file that may not exist. Handle the exception if the file is missing, and use the finally block to print a message ensuring that some crucial cleanup actions have been performed.

Here's the code to place in transcript_keeper.py:

def preserve_script():
    try:
        with open('/home/labex/project/sacred_script.txt', 'r') as file:
            contents = file.read()
            print(contents)
    except FileNotFoundError:
        print('The sacred script cannot be found.')
    finally:
        print('Ensuring the preservation environment remains intact.')

preserve_script()

Now, run your script in the terminal with the following command:

python3 ~/project/transcript_keeper.py

If the sacred_script.txt does not exist, it should display the error message, followed by the finally block message:

The sacred script cannot be found.
Ensuring the preservation environment remains intact.

Engraving the Logic onto Stone

Having created the basic structure, it is now time to engrave the safeguarding logic onto stone, making it permanent. In this step, you will enhance the transcript-keeper with actions that must always execute, irrespective of successful read operations or not.

Modify the transcript_keeper.py to include a simulated cleanup action in the finally block that represents saving the state of the script environment to a log file.

Add this at the end of your finally block in transcript_keeper.py:

def preserve_script():
    try:
        with open('/home/labex/project/sacred_script.txt', 'r') as file:
            contents = file.read()
            print(contents)
    except FileNotFoundError:
        print('The sacred script cannot be found.')
    finally:
        print('Ensuring the preservation environment remains intact.')
        with open('/home/labex/project/preservation_log.txt', 'a') as log_file:
            log_file.write('Preservation check completed\n')

preserve_script()

Run the modified script again and check that preservation_log.txt has the log entry.

The information below should be displayed on your terminal:

$ python3 ~/project/transcript_keeper.py
The sacred script cannot be found.
Ensuring the preservation environment remains intact.
$ cat /home/labex/project/preservation_log.txt
Preservation check completed

Summary

In this lab, you embarked on a journey to ancient Egypt, where you used your knowledge of Python's finally block to secure the continuity of the Queen's sacred scripts. With the finally block, you created a robust system that guarantees certain actions, such as logging, are performed irrespective of any errors encountered during execution.

Through this mystical adventure, you've learned the importance of cleanup actions and their implementation using Python's finally block. This safety net ensures that the critical operations of your script will complete, instilling confidence in your code's resilience. May your journey through the realm of Python continue to be as enlightening as the ancient wisdom of Egypt.

Other Python Tutorials you may like