0% found this document useful (0 votes)
16 views29 pages

07 20241021 ExceptionHandling FileHandling

The document covers exception handling and file handling in Python, detailing how to manage errors using try, except, else, and finally blocks, as well as the creation of custom exceptions. It also explains file operations, including reading and writing both binary and text files, with examples demonstrating best practices. Key concepts include handling specific exceptions, using context managers for file operations, and parsing structured data from text files.

Uploaded by

scs623170
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views29 pages

07 20241021 ExceptionHandling FileHandling

The document covers exception handling and file handling in Python, detailing how to manage errors using try, except, else, and finally blocks, as well as the creation of custom exceptions. It also explains file operations, including reading and writing both binary and text files, with examples demonstrating best practices. Key concepts include handling specific exceptions, using context managers for file operations, and parsing structured data from text files.

Uploaded by

scs623170
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Exception handling

&
File handling

Prof. Murali Krishna Gurram


Dept. of Geo-Engineering & RDT
Centre for Remote Sensing, AUCE
Andhra University, Visakhapatnam – 530 003
Dt. 21/10/2024
Basic Elements of Python

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.

 These errors, also known as exceptions, can interrupt the


normal flow of a program.

 Using exception handling allows the programmer to gracefully


deal with such events, ensuring that the program continues or
exits smoothly.

 Exception handling is a crucial part of robust Python


programming. By using the try, except, else, and finally blocks,
you can manage errors gracefully and ensure your program
behaves as expected under various conditions.
 Custom exceptions: Allows you to define your own errors for
specific use cases.
Exception Handling in Python
Common Types of Exceptions:
Python has various built-in exceptions, such as:

• ZeroDivisionError: Occurs when a division by zero is attempted.

• ValueError: Raised when a function receives an argument of the


right type but with an inappropriate value.

• FileNotFoundError: Raised when a file operation (like opening a


file) fails because the file doesn't exist.

• IndexError: Raised when trying to access an index that is out of


range in a list or tuple.
Exception Handling in Python
Common Types of Exceptions:
Basic Exception Handling Syntax
The try, except, else, and finally blocks are used to handle exceptions in Python:

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:

Example 1: Handling Division by Zero


try:
result = 10 / 0
except ZeroDivisionError:
print("Error: You cannot divide by zero!")

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:

Example 2: Handling Multiple Exceptions


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! Please enter a valid number.")

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.

• The exception is caught and handled in the try-except block.


Exception Handling in Python
Common Types of Exceptions:
Creating Custom Exceptions
• You can create your own exceptions by defining a class that inherits
from Python’s built-in 'Exception' class.
class CustomError(Exception):
pass

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.

• It is raised and caught in the try-except block.


Exception Handling in Python
Best Practices for Exception Handling
• Avoid bare except: Always specify the type of exception you're
handling to prevent catching unintended errors.

• Handle specific exceptions: Handle exceptions that you expect,


rather than general ones like Exception.

• Use finally for cleanup: Always use the finally block to release
resources or perform necessary cleanup.

• Keep it concise: Don’t overuse exceptions; only use them when


necessary, and make sure they are easy to understand.
File Handling in Python
File Handling in Python
Best Practices for Exception Handling
File Handling in Python allows you to perform typical file
operations such as..
 Creating files
 Reading files
 Writing files
 Deleting files

There are two main types of files that Python can handle:

 Text Files: Files containing text data (e.g., .txt, .csv).

 Binary Files: Files containing binary data (e.g., .png, .bin).


File Handling in Python
1. Writing and Reading Binary Data
 Binary data is stored in a format that is not human-readable
and is often used for files such as images, videos, and other
media.

 When handling binary data in Python, you need to open the file
in binary mode ('b').

file = open("file.bin", "wb") # 'wb' means write binary

• 'wb': Write binary mode. It creates a new file or overwrites


an existing one.

• 'rb': Read binary mode.


File Handling in Python
1. Writing and Reading Binary Data
Writing Binary Data
 You can write binary data using the write() method.
data = bytes([120, 3, 255, 0, 100]) # Binary data in byte format

with open("binary_file.bin", "wb") as file:


file.write(data)

print("Binary data written successfully.")

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

with open("binary_file.bin", "wb") as file:


file.write(data)

print("Binary data written successfully.")

Explanation:
• The file is opened in 'rb' mode, which stands for read binary.

• The read() method reads the contents as bytes.


File Handling in Python
2. Writing and Parsing Text Files
Text files are human-readable and often contain characters,
numbers, or structured data. You will learn how to:

• Write text to a file.

• Read and parse text from a file.


File Handling in Python
2. Writing and Parsing Text Files
Writing to a Text File:
• To write text to a file, open it in write mode ('w') or append
mode ('a').

Example: Writing Text Data


with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python file handling is easy.\n")

print("Text written to file.")

Explanation:
• The file is opened in 'w' mode, which means it will create a new file or
overwrite an existing one.

• The write() method writes strings to the file.


File Handling in Python
2. Writing and Parsing Text Files
Writing to a Text File:

Example: Appending to a Text File.


with open("example.txt", "a") as file:
file.write("This line will be appended.\n")

print("Text appended to file.")

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.

Example: Reading the Entire File


with open("example.txt", "r") as file:
content = file.read()

print("File content:\n", content)

Explanation:
• The file is opened in 'r' mode (read mode).

• read() reads the entire file and stores it in a string.


File Handling in Python
2. Writing and Parsing Text Files
Reading Line by Line:

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()

for line in lines:


print(line.strip())

Explanation:
• readlines() reads all lines and returns them as a list of strings.

• Useful for processing files where each line is a separate


record.
File Handling in Python
3. Parsing Text Files

• Often, text files contain structured data that needs to be


parsed.

• For example, consider a CSV file with comma-separated


values.
File Handling in Python
3. Parsing Text Files
Parsing a Simple Text File
• Assume we have a text file (data.txt) with the following
content:
John,25,Developer
Jane,30,Designer

• We can parse this file to extract the values.


with open("data.txt", "r") as file:
for line in file:
name, age, occupation = line.strip().split(",")
print(f"Name: {name}, Age: {age}, Occupation: {occupation}")

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.

Using the 'os' and 'shutil' Modules

• os.path: Provides functions to handle file paths.

• shutil: Used for file operations such as copying or moving files.


File Handling in Python
4. Working with File Paths (Optional Advanced Topic)

Example:
import os
import shutil

# Copy a file
shutil.copy("example.txt", "copy_of_example.txt")

# Check if a file exists


if os.path.exists("copy_of_example.txt"):
print("File copied successfully.")
Q&A

You might also like