0% found this document useful (0 votes)
2 views6 pages

Unit_5_File_handling_Exception_handling

This document covers file handling and exception handling in Python. It explains how to open, read, write, and close files, along with best practices like using the 'with' statement. Additionally, it details exception management, including raising exceptions and creating custom exceptions, with relevant examples for each concept.

Uploaded by

tkulkarni2007
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)
2 views6 pages

Unit_5_File_handling_Exception_handling

This document covers file handling and exception handling in Python. It explains how to open, read, write, and close files, along with best practices like using the 'with' statement. Additionally, it details exception management, including raising exceptions and creating custom exceptions, with relevant examples for each concept.

Uploaded by

tkulkarni2007
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/ 6

Unit 5

1. File Handling in Python: File handling in Python involves interacting with files on your
computer to read data from them or write data to them. Python provides several built-in
functions and methods for creating, opening, reading, writing, and closing files.

i. Opening a File in Python: To perform any file operation, the first step is to open the
file. Python's built-in open() function is used to open files in various modes, such as
reading, writing, and appending.
Syntax:
file = open("filename", "mode")
Where, filename is the name of the file to open and mode is the mode in which the
file is opened (e.g., 'r' for reading, 'w' for writing, 'a' for appending).
Study resource: https://www.tutorialspoint.com/python/python_file_handling.htm
Example 1:
# Opening a file in read mode
file = open("example.txt", "r")

# Opening a file in write mode


file = open("example.txt", "w")

# Opening a file in append mode


file = open("example.txt", "a")

# Opening a file in binary read mode


file = open("example.txt", "rb")

Example 2: (practical no 22)


# Open a file
f1 = open("file1.txt", "r")
print ("Name of the file: ", f1.name)
print ("Closed or not: ", f1.closed)
print ("Opening mode: ", f1.mode)
f1.close()

ii. Reading a File in Python: Reading a file in Python involves opening the file in a
mode that allows for reading, and then using various methods to extract the data from
the file. Python provides several methods to read data from a file –
read() − Reads the entire file.
readline() − Reads one line/first line at a time.
readlines − Reads all lines into a list.
Example 3-a: (practical no 22) The with statement is a best practice in Python
for file operations because it ensures that the file is automatically closed when
the block of code is exited, even if an exception occurs.
with open("file1.txt", "r") as file:
content = file.read()
print(content)

Example 3-b: (practical no 22)


f1 = open("file1.txt", "r")
content = f1.read()
print(content)
f1.close()

Example 4: Using readline() method (it will read first line)


with open("file1.txt", "r") as file:
line = file.readline()
print(line)

Example 5: Using readline() method (it will all content)


with open("example.txt", "r") as file:
line = file.readline()
while line:
print(line, end='')
line = file.readline()

iii. Writing to a File in Python: Writing to a file in Python involves opening the file in a
mode that allows writing, and then using various methods to add content to the file.
To write data to a file, use the write() or writelines() methods.
Example 6: (practical no 22)
with open("file1.txt", "w") as file:
file.write("Hello, World!")
print ("Content added Successfully!!")

Example 7: (practical no 22)


with open("file1.txt", "a") as file:
file.write("Hello, GPA!")
print ("Content appended Successfully!!")

iv. Closing a File in Python: We can close a file in Python using the close() method.
Closing a file is an essential step in file handling to ensure that all resources used by
the file are properly released. It is important to close files after operations are
completed to prevent data loss and free up system resources.
Example 8:
f1 = open("file1.txt", "w")
f1.write("This is an example.")
f1.close()
print ("File closed successfully!!")

2. Exception Handling in Python: Exception handling in Python refers to managing


runtime errors that may occur during the execution of a program. In Python, exceptions
are raised when errors or unexpected situations arise during program execution, such as
division by zero, trying to access a file that does not exist, or attempting to perform an
operation on incompatible data types.

i. What is Exception?- An exception is an event, which occurs during the


execution of a program that disrupts the normal flow of the program's
instructions. In general, when a Python script encounters a situation that it cannot
cope with, it raises an exception. An exception is a Python object that represents
an error.

ii. Handling an Exception in Python:


Syntax:
try:
You do your operations here
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

 A single try statement can have multiple except statements. This is useful
when the try block contains statements that may throw different types of
exceptions.
 You can also provide a generic except clause, which handles any
exception.
 After the except clause(s), you can include an else clause. The code in the
else block executes if the code in the try: block does not raise an
exception.
 The else block is a good place for code that does not need the try: block's
protection.
Example 1:
try:
fh = open("testfile1.txt", "r+")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: cant find file or read data")
else:
print ("Written content in the file successfully")
fh.close()

iii. The except Clause with No Exceptions: This kind of a try-except statement
catches all the exceptions that occur.
Syntax:
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:
If there is no exception then execute this block.

iv. The except Clause with Multiple Exceptions: You can also use the same except
statement to handle multiple exceptions.
Syntax:
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.
v. The try-finally Clause: You can use a finally: block along with a try: block. The
finally block is a place to put any code that must execute, whether the try-block
raised an exception or not.
Syntax:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Example 2:
try:
fh = open("testfile1.txt", "r+")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: cant find file or read data")

Example 3:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")

vi. Raising an Exceptions: You can raise exceptions in several ways by using the
raise statement.
Syntax:
raise [Exception [, args [, traceback]]]

Here, Exception is the type of exception (for example, NameError) and argument
is a value for the exception argument. The argument is optional; if not supplied,
the exception argument is None. The final argument, trace back, is also optional
(and rarely used in practice), and if present, is the traceback object used for the
exception.
Resources:
Built in Exceptions: https://www.programiz.com/python-programming/exceptions
User defined Exceptions: https://www.programiz.com/python-programming/user-
defined-exception

vii. Python User defined / Custom Exceptions: In Python, we can define custom
exceptions by creating a new class that is derived from the built-in Exception
class.
Example 4: (practical no 23)
# define Python user-defined exceptions
class InvalidAgeException(Exception):
"Raised when the input value is less than 18"
pass

# you need to guess this number


number = 18

try:
input_num = int(input("Enter a number: "))
if input_num < number:
raise InvalidAgeException
else:
print("Eligible to Vote")

except InvalidAgeException:
print("Exception occurred: Invalid Age")

You might also like