UNIT-4 Exception -f File Handling
UNIT-4 Exception -f File Handling
i 5 > 2:
print("Five is greater than two!")
Output:
Cell In[2], line 1
i 5 > 2:
^
SyntaxError: invalid syntax
Example-2:
if 5 > 2:
print("Five is greater than two!")
Output:
Cell In[3], line 2
print("Five is greater than two!")
^
IndentationError: expected an indented block after 'if' statement on line 1
2.Logical errors:
● These errors do not cause the program to crash, but they lead to incorrect results. They are often the most
challenging to debug because the code runs without any error messages.
Example:
def add(a,b):
result=a-b
return result
add(2,3)
Output:
-1
In this case, the function is intended to add two numbers, but due to a logical error (subtracting instead of adding), it
will not produce the correct result.
a=10
b=input("enter b:")
c=a//b
print(c)
Output:
enter b:2
--------------------------------------------------------------------- ------
TypeError Traceback (most recent call last)
Cell In[6], line 3
1 a=10
2 b=input("enter b:")
----> 3 c=a//b
4 print(c)
Common exception
. NoName of the Built-in
ExceptionExplanation
1. SyntaxError It is raised when there is an error in the syntax of the Python code.
3. IOError It is raised when the file specified in a program statement cannot beopened.
4 KeyboardInterrupt It is raised when the user accidentally hits the Delete or Esc key while
executing a program due to which the normal flow of the program is
interrupted.
6 EOFError It is raised when the end of file condition is reached without readingany
data by input().
12 OverFlowError It is raised when the result of a calculation exceeds the maximumlimit for
numeric data type.
Exception Handling:
A runtime error, also known as an exception, occurs during the execution of a
program when something unexpected or erroneous happens. Exception
handling is a mechanism in programming languages, including Python, that
allows developers to manage and respond to these runtime errors in a
controlled manner. Handling exceptions helps prevent a program from crashing and allows for graceful error recovery.
In Python, the try, except, else, and finally blocks are used for exception handling:
Exception handling is the way to handle the Exception so that the other part of the code can be executed without any
disruption.
1.TryBlock:
The try block encloses the code that might raise an exception. If an exception
occurs within this block, it is caught by the corresponding except block.
Example 1
try:
# Code that might raise a runtime error
result = 10 / 0 # Example: Division by zero
except ZeroDivisionError:
# Code to handle the specific exception
print("Cannot divide by zero!")
You can have multiple except blocks to handle different types of exceptions.
Example :
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
Example:
try:
# Code that might raise a runtime error
result = 10 / 0 # Example: Division by zero
except Exception as e:
# Code to handle the exception
print(f"An error occurred: {e}")
4. Else Block:
The else block is executed if no exception occurs in the try block. Example:
try:
value = int(input("Enter a number: "))
result = 10 / value
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print(f"The result is: {result}")
5. Finally Block:
● The finally block is executed regardless of whether an exception occurs or not. It's often used for cleanup
operations.
Example:
try:
file = open("example.txt", "r")
# Code that might raise an exception while reading the file except FileNotFoundError:
print("File not found!")
finally:
# Code that will be executed no matter what
file.close()
Example:class
AgeError(Exception):
pass
class TooYoungError(AgeError):
pass
class TooOldError(AgeError):
pass
while True:
try:
raise TooYoungError
elif age > 100:
raise TooOldError
else:
break
except ValueError:
print("Invalid input. Please enter a valid integer for age.")
except TooYoungError:
print("Sorry, you are too young to use this service. Please try again.") except TooOldError:
print("Sorry, you are too old to use this service. Please try again.")
● In Python, the raise statement is used to raise an exception explicitly. This allows you to signal that a particular
condition or situation has occurred, and the corresponding exception should be handled by the appropriate except block.
Here's a brief explanation and an example:
raise Statement:
The raise statement is used to raise an exception manually. It generally follows the
format:
Example Code:
try:
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
raise ValueError("The number is odd.")
except ValueError as ve:
print(f"Invalid input: {ve}")
File Handling in Python
Files
• Files are named locations on disk to store related information.
They are used to permanently store data in a non-volatile
memory (e.g. hard disk).
• Since Random Access Memory (RAM) is volatile (which loses its
data when the computer is turned off), we use files for future
use of the data by permanently storing them.
• When we want to read from or write to a file, we need to open
it first. When we are done, it needs to be closed so that the
resources that are tied with the file are freed.
• Hence, in Python, a file operation takes place in the following
order:
– Open a file
– Read or write (perform operation)
– Close the file
• Binary file
• Text file
Binary files in Python
• All binary files follow a specific format. We can
open some binary files in the normal text editor
but we can’t read the content present inside the
file. That’s because all the binary files will be
encoded in the binary format, which can be
understood only by a computer or machine.
• For handling such binary files we need a specific
type of software to open it.
• For Example, You need Microsoft word software
to open .doc binary files. Likewise, you need a pdf
reader software to open .pdf binary files and you
need a photo editor software to read the image
files and so on.
Binary files in Python (cont…1)
• Most of the files that we see in our computer
system are called binary files.
• Example:
• Document files: .pdf, .doc, .xls etc. • Image
files: .png, .jpg, .gif, .bmp etc. • Video files:
.mp4, .3gp, .mkv, .avi etc. • Audio files: .mp3,
.wav, .mka, .aac etc. • Database files: .mdb,
.accde, .frm, .sqlite etc. • Archive files: .zip,
.rar, .iso, .7z etc. • Executable files: .exe, .dll,
.class etc.
Text files in Python
• A text file is usually considered as sequence of
lines. Line is a sequence of characters (ASCII),
stored on permanent storage media. Although
default character coding in python is ASCII but
supports Unicode as well.
• in text file, each line is terminated by a special
character, known as End of Line (EOL). From
strings we know that \n is newline character.
• at the lowest level, text file is collection of bytes.
Text files are stored in human readable form. • they
can also be created using any text editor.
Text files in Python (Cont…1)
• Text files don’t have any specific encoding and
it can be opened in normal text editor itself. •
Example:
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc. •
Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
Opening or Creating a New File in Python
• The method open() is used to open an existing file or
creating a new file. If the complete directory is not given
then the file will be created in the directory in which the
python file is stored. The syntax for using open()
method is given below.
– Syntax:
– file_object = open( file_name, “Access Mode”, Buffering ) •
The open method returns file object which can be stored
in the name file_object (file-handle).
• File name is a unique name in a directory. The open()
function will create the file with the specified name if it
is not already exists otherwise it will open the already
existing file.
Opening Files in Python
(cont…1) • The access mode
it is the string which tells in what mode the file should
be opened for operations. There are three different
access modes are available in python.
• Reading: Reading mode is crated only for reading the
file. The pointer will be at the beginning of the file. •
Writing: Writing mode is used for overwriting the
information on existing file.
• Append: Append mode is same as the writing mode.
Instead of over writing the information this mode
append the information at the end.
• Below is the list of representation of various access
modes in python.
Opening Files in Python
(cont…2) Access modes in Text Files
• ‘r' – Read Mode: Read mode is used only to read data
from the file.
• ‘w' – Write Mode: This mode is used when you want to
write data into the file or modify it. Remember write
mode overwrites the data present in the file.
• ‘a' – Append Mode: Append mode is used to append
data to the file. Remember data will be appended at
the end of the file pointer.
• ‘r+' – Read or Write Mode: This mode is used when we
want to write or read the data from the same file. • ‘a+' –
Append or Read Mode: This mode is used when we want
to read data from the file or append the data into the
same file.
Opening Files in Python
(cont…3) Access modes in Binary Files
• ‘wb’ – Open a file for write only mode in the
binary format.
• ‘rb’ – Open a file for the read-only mode in the
binary format.
• ‘ab’ – Open a file for appending only mode in the
binary format.
• ‘rb+’ – Open a file for read and write only mode
in the binary format.
• ‘ab+’ – Open a file for appending and read-only
mode in the binary format.
Opening Files in Python
(cont…4) What is Buffering ?
• Buffering is the process of storing a chunk of a
file in a temporary memory until the file loads
completely. In python there are different
values can be given. If the buffering is set to 0
, then the buffering is off. The buffering will be
set to 1 when we need to buffer the file.
Opening Files in Python
(cont…5) Examples Opening a file:
# open file in current directory
• f = open("test.txt“, “r”)
Output:
Hello World
Output:
*‘Hello World\n’, ‘Hello Python\n’, ‘Good Morning’+
Here we are reading all the lines present inside
the text file including the newline characters.
Reading Information in the File (cont…6)
Output:
Hello World
Hello Python
Good Morning
How are You
Write to a Python File
• In order to write data into a file, we must open the file in
write mode.
• We need to be very careful while writing data into the file
as it overwrites the content present inside the file that you
are writing, and all the previous data will be erased.
• We have two methods for writing data into a file as shown
below.
– write(string)
– writelines(list)
• Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World”)
The above code writes the String ‘Hello World’ into the ‘test.txt’
file.
Write to a Python File (cont…1)
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.write(“Hello World\n”)
my_file.write(“Hello Python”)
•The first line will be ‘Hello World’ and as we have mentioned \n character, the
cursor will move to the next line of the file and then write ‘Hello Python’.
•Remember if we don’t mention \n character, then the data will be written
continuously in the text file like ‘Hello WorldHelloPython’
Example 3:
fruits = *“Apple\n”, “Orange\n”, “Grapes\n”, “Watermelon”+
my_file = open(“C:/Documents/Python/test.txt”, “w”)
my_file.writelines(fruits)
The above code writes a list of data into the ‘test.txt’ file simultaneously.
Append in a Python
File
To append data into a file we must open the file in
‘a+’ mode so that we will have access to both
the append as well as write modes.
Example 1:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“Strawberry”)
The above code appends the string ‘Strawberry’ at the end of the ‘test.txt’ file
Example 2:
my_file = open(“C:/Documents/Python/test.txt”, “a+”)
my_file.write (“\nGuava”)