07 20241021 ExceptionHandling FileHandling
07 20241021 ExceptionHandling FileHandling
&
File handling
1. Exception handling
2. File handling
• Writing and reading binary data
• Writing and parsing text files
Exception Handling in Python
Exception Handling in Python
Exception Handling :
Exception Handling in Python refers to the mechanism of
catching and managing errors that may arise during the
execution of a program.
try:
# Code that may raise an exception
risky_code()
except ExceptionType:
# Code that runs if the exception occurs
handle_exception()
else:
# Code that runs if no exceptions occur
normal_flow()
finally:
# Code that always runs, even if exceptions occur
cleanup()
Exception Handling in Python
Common Types of Exceptions:
Explanation:
• In this example, when 10 / 0 is attempted.
• Python raises a ZeroDivisionError, which is caught by the except block, preventing the
program from crashing.
Exception Handling in Python
Common Types of Exceptions:
Explanation:
• This example shows how multiple exceptions can be handled.
• If the user enters an invalid value (non-numeric), a ValueError is raised.
• If the input is zero, a ZeroDivisionError is raised.
Exception Handling in Python
Common Types of Exceptions:
The 'else' Block
The 'else' block is executed only if no exceptions are raised in the 'try' block.
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Invalid input!")
else:
print("The result is:", result)
Explanation:
• If the input is valid and no exceptions are raised, the code in the else block will execute
and print the result.
Exception Handling in Python
Common Types of Exceptions:
The 'finally' Block
• The 'finally' block always executes, regardless of whether an
exception is raised or not. This is often used for cleanup actions, such
as closing files or releasing resources.
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
file.close()
print("File closed.")
Explanation:
• Even if the file is not found and an exception is raised, the finally block ensures that the
file (if opened) is closed properly.
Exception Handling in Python
Common Types of Exceptions:
Raising Exceptions
• You can manually raise exceptions using the 'raise' keyword.
def check_age(age):
if age < 18:
raise ValueError("Age must be 18 or above.")
return True
try:
check_age(16)
except ValueError as e:
print(e)
Explanation:
• In this example, the check_age() function raises a ValueError if the age is less than 18.
try:
raise CustomError("This is a custom error.")
except CustomError as e:
print(e)
Explanation:
• A custom exception CustomError is created by inheriting from the Exception class.
• Use finally for cleanup: Always use the finally block to release
resources or perform necessary cleanup.
There are two main types of files that Python can handle:
When handling binary data in Python, you need to open the file
in binary mode ('b').
Explanation:
• bytes() converts a list of integers (0–255) to a byte object.
• The write() method writes the binary data into the file.
• The file is closed automatically when using the with
statement.
File Handling in Python
1. Writing and Reading Binary Data
Reading Binary Data
• Binary data can be read using the read() method.
data = bytes([120, 3, 255, 0, 100]) # Binary data in byte format
Explanation:
• The file is opened in 'rb' mode, which stands for read binary.
Explanation:
• The file is opened in 'w' mode, which means it will create a new file or
overwrite an existing one.
Explanation:
• The file is opened in 'a' mode, meaning new text is appended to the end of
the file, without overwriting the existing content.
File Handling in Python
2. Writing and Parsing Text Files
Reading from a Text File:
• You can read text from a file using the read(), readline(), or
readlines() methods.
Explanation:
• The file is opened in 'r' mode (read mode).
Example:
with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line.strip()) # Strip removes any extra newline characters
line = file.readline()
Explanation:
• readline() reads one line at a time.
• This approach is useful for processing large files where reading the
entire file at once is inefficient.
File Handling in Python
2. Writing and Parsing Text Files
Reading All Lines as a List:
Example:
with open("example.txt", "r") as file:
lines = file.readlines()
Explanation:
• readlines() reads all lines and returns them as a list of strings.
Explanation:
• Each line is read and stripped of newline characters.
• The split() method splits the line into values using a comma as the
delimiter.
• Each value is stored in the respective variables (name, age, occupation).
File Handling in Python
4. Working with File Paths (Optional Advanced Topic)
• When working with files, handling file paths can be important,
especially if you are dealing with directories or different
operating systems.
Example:
import os
import shutil
# Copy a file
shutil.copy("example.txt", "copy_of_example.txt")