0% found this document useful (0 votes)
12 views

ExceptionAndFileHandling

nfgnhfrhr

Uploaded by

pawan kamal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

ExceptionAndFileHandling

nfgnhfrhr

Uploaded by

pawan kamal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 52

Exception & File Handling

Exception Handling
❑ An exception is an error that occurs while a program is running. When an error
happens, Python stops the program unless the error is handled. Exception
handling allows us to manage these errors so our program doesn’t crash and can
continue running or handle the error gracefully.

❑ Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).

When these exceptions occur, the Python interpreter stops the current process
and passes it to the calling process until it is handled. If not handled, the program
will crash.

❑ Syntax:
try:
#statements which could generate exception
except:
#Soloution of generated exception
Handling Exception

3
Multiple Exception
You can handle different types of exceptions with multiple except blocks.
python

try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
Finally Clause
❑ The finally code block is also a part of exception handling.
When we handle exception using the try and except block, we
can include a finally block at the end.
❑ The finally block is always executed, so it is generally used
for doing the concluding tasks like closing file resources or
closing database connection or may be ending the program
execution with a delightful message.

Syntax:
try:
#statements which could generate exception
except:
#solution of generated exception
finally:
#block of code which is going to execute in any situation
using else and finally
•else: Runs if there were no exceptions.
•finally: Runs no matter what, even if there’s an exception.

try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Please enter a valid number.")
else:
print("The result is:", result)
finally:
print("This will always run.")
Exception Handling

7
ArithmeticError
•This is a base class for errors related to arithmetic operations.
•Example: Division by zero, overflow, or issues in numeric operations.
•Common Subclasses:
• ZeroDivisionError: Raised when dividing by zero.
• OverflowError: Raised when a number is too large to be represented.

Example-
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")

FloatingPointError
•This exception is raised for errors related to floating-point operations.
•It is uncommon and usually requires enabling floating-point error checking with
specific modules, as Python handles most floating-point issues automatically.
Example-

import math
try:
math.exp(1000) # May raise OverflowError in some systems
except OverflowError:
print("Floating point overflow!")

IOError
•Raised when an input/output operation fails, like reading or writing files.
•Common Causes: File not found, permission errors, etc

•Example-
try:
with open('non_existent_file.txt', 'r') as file:
content = file.read()
except IOError:
print("File not found or cannot be opened.")
SyntaxError
•Raised when there is an error in the syntax of the Python code.
•Note: This error occurs during the parsing of code, so it’s usually detected before
the program runs.

Example-
try:
exec("print('Hello') print('World')") # Missing semicolon or newline
except SyntaxError:
print("Syntax error in the code.")

IndentationError
•A specific type of SyntaxError, raised when code indentation is incorrect.
Example-
try:
exec("""
def fun():
print("hello")
fun() # This line has incorrect indentation to trigger IndentationError
""")
except IndentationError:
print("Indentation error in the code.")
except SyntaxError:
print("Syntax error in the code.")
ValueError
•Raised when a function receives an argument of the correct type but inappropriate value.

Example
try:
number = int("hello") # Cannot convert a string to an integer
except ValueError:
print("Invalid value for integer conversion.")

RuntimeError
This is a base class for errors that occur during runtime. It generally acts as a catch-all for
unexpected runtime issues.

Example-
try:
# An example of a recursive function that causes a RuntimeError (recursion limit reached)
def recursive_function():
return recursive_function()
recursive_function()
except RuntimeError:
print("Runtime error: Recursion limit reached.")
IndexError
An IndexError occurs when you try to access an index in a list (or other sequence)
that is out of range. This can happen if you try to access an element at an index that
doesn't exist, such as using an index that is greater than the highest index in the list
or negative indexes that aren't valid.

Example-

try:
my_list = [10, 20, 30]
print(my_list[5]) # This will cause an IndexError because index 5 is out of range
except IndexError:
print("IndexError: List index out of range")
Handling Exception…

13
Handling Exception…

14
Handling Exception…

15
Raising Custom errors
In python, we can raise custom errors by using the
`raise` keyword.

salary = int(input("Enter salary amount: "))


if not 2000 < salary < 5000:
raise ValueError("Not a valid salary")

In Python, you can create custom exceptions by defining your


own exception classes. These custom exceptions allow you to
handle specific error cases in your program with more clarity and
flexibility.
# Step 1: Define the custom exception class
class MyCustomError(Exception):
"""Custom Exception for handling specific errors."""
pass

# Step 2: Function that raises the custom exception


def check_value(value):
if value < 0:
raise MyCustomError("Value cannot be negative!") # Raise the custom exception
else:
print("Value is valid:", value)

# Step 3: Try to execute the function and catch the custom exception
try:
check_value(-5) # This will raise MyCustomError
except MyCustomError as e:
print(f"Caught an error: {e}") # Handle the error
File

File is a named location on disk to store related information


It is used to permanently store data in non-volatile memory
In Python, a file operation take place in the following order
• Open a file
• Read or write (perform operation)
• Close the file
Open a file

We have to open a file using built-in function open()


This function returns a file object, also called a handle, it is
used to read or modify the file
We can specify the mode while opening a file.
r – Read
w – Write
a – Append
Syntax:
file object= open(filename [,accessmode][, buffering])
Opening a File
◼ Syntax
file object = open(file_name [, access_mode][, buffering])

◼ file_name − The file_name argument is a string value that


contains the name of the file that you want to access.
◼ access_mode − The access mode determines the mode in
which the file has to be opened, i.e., read, write, append,
etcThis is an optional parameter and the default file access
mode is read (r).
◼ buffering − If the buffering value is set to 0, no buffering takes
place. If the buffering value is 1, line buffering is performed while
accessing a file. If you specify the buffering value as an integer
greater than 1, then buffering action is performed with the
indicated buffer size. If negative, the buffer size is the system
default(default behavior).

20
Opening a File
filename: name of the file that we want to access
accessmode: read, write, append etc.
buffering: 0 – no buffering
1- line buffering
integer greater than 1- buffering action is performed
with the indicated buffer size

Example:
f=open(“abc.txt”,’r’) # open file in current directory
f=open(“C:/Python33/sample.txt”,’r’)#specifying full path
Opening
FileaOpening
File Modes

22
Modes…

23
Modes…

24
Attributes of file object

Once a file is opened , we have one file object, which contain


various info related to that file

1. file.closed – Returns true if the file is closed, False


otherwise
2. file.mode – Returns access mode with wich file was
opened
3. file.name- Name of the file
4. file.softspace – Returns 0 if space is explicitly required
with print, 1 otherwise
File Object Attributes

26
Example
fo.open(“abc.txt”,”w”)
print(“Name of the file:”,fo.name)
print(“Closed or not :”,fo.closed)
print(“Opening mode :”,fo.mode)
print(“Softspace flag :”,fo.softspace)

Name of the file: abc.txt


Closed or not:False
Opening mode:w
Softspace flag:0
Closing a File

File closing is done with close() method


Syntax:
fileobject.close()
Example:
f=open(“bin.tx”,wb)
proint(“Name of the file:”,fo.name)
fo.close()
print(“File closed”)
Output
Name of the file: bin.txt
File closed
Reading File
Reading a File

File object includes the following methods to read data from the
file.
•read(chars): reads the specified number of characters starting
from the current position.
•readline(): reads the characters starting from the current reading
position up to a newline character.
•readlines(): reads all lines until the end of file and returns a list
object.
Reading Files
name = open("filename“,”mode”,buffering)
◼ opens the given file for reading, and returns a file object

name.read() - file's entire contents as a string


name.readline() - next line from file as a string
name.readlines() - file's contents as a list of lines
◼ the lines from a file object can also be read using a for loop

>>> f = open("hours.txt")
>>> f.read()
'123 Susan 12.5 8.1 7.6 3.2\n
456 Brad 4.0 11.6 6.5 2.7 12\n
789 Jenn 8.0 8.0 8.0 8.0 7.5\n'
File reading in Python
File reading in Python

# read the entire file as one string


with open('filename.txt') as f:
data = f.read()
# Iterate over the lines of the File
with open('filename.txt') as f:
for line in f :
print(line, end=' ‘)
# process the lines
The following example demonstrates reading a line from the file
>>>f=open('C:\myfile.txt') # opening a file
>>> line1 = f.readline() # reading a line
>>> line1
'This is the first line. \n'
>>> line2 = f.readline() # reading a line
>>> line2
'This is the second line.\n'
>>> line3 = f.readline() # reading a line
>>> line3
'This is the third line.'
>>> line4 = f.readline() # reading a line
>>> line4
''
>>> f.close() # closing file object
we have to open the file in 'r' mode. The readline() method will
return the first line, and then will point to the second line.
Reading all Lines

The following reads all lines using the readlines() function

f= open('C:\myfile.txt') # opening a file


>>> lines = f.readlines() # reading all lines
>>> lines
'This is the first line. \nThis is the second
line.\nThis is the third line.'
>>> f.close() # closing file object
Use for loop to read a file

f=open('C:\myfile.txt’)
for line in f:
print(line)
f.close()
Deleting a file
Removing a file

We can delete a file by using remove() method


Syntax:
os.remove(filename)
Example:
import os
os.remove(“Newtest.txt”)
print(“File deleted”)
File writing in Python

Similarly, for writing data to files, we have to use open() with 'wt' mode
Also, we have to use the write() function to write into a file.
# Write text data to a file
with open('filename.txt' , 'wt') as f:
f.write ('hi there, this is a first line of file.\n’)
f.write ('and another line.\n’)
Output
hi there, this is a first line of file.
and another line.
Writing Files
name = open("filename", "w")
name = open("filename", "a")
◼ opens file for write (deletes previous contents), or
◼ opens file for append (new data goes after previous data)

name.write(str) - writes the given string to the file


name.close() - saves file once writing is done

>>> out = open("output.txt", "w")


>>> out.write("Hello, world!\n")
>>> out.write("How are you?")
>>> out.close()
>>> open("output.txt").read()
Hello, world!
How are you?
File Input Template
◼ A template for reading files in Python:

name = open("filename")
for line in name:
statements

>>> input = open("hours.txt")


>>> for line in input:
... print(line.strip()) # strip()
removes \n
123 Susan 12.5 8.1 7.6 3.2
456 Brad 4.0 11.6 6.5 2.7 12
789 Jenn 8.0 8.0 8.0 8.0 7.5
with statement
With statement is used when we have two related operations which
we would like to execute as a pair, with a block of code in between
Example: opening a file, manipulating a file and closing it
with open(“output.txt”,”w”) as f:
f.write(“Hello Python!”)

The above statement automatically close the file after the nested
block of code.
The advantage of using with statement is that it is guaranteed to
close the file.
If an exception occurs before the end of the block, it will close the
file before the exception is caught by an outer exception handler
Renaming a file
Renaming a file

The os module Python provides methods that help to perform file-


processing operations, such as renaming and deleting.
To rename an existing file, rename() method is used
It takes two arguments, current file name and new file name
Syntax:
os.rename(current_file_name, new_file_name)
Example:
import os
os.rename(“test.txt”,”Newtest.txt”)
print(“File renamed”)
writelines method
The writelines() method in Python writes a sequence of
strings to a file. The sequence can be any iterable object,
such as a list or a tuple.
Here's an example of how to use the writelines() method:
f = open('myfile.txt', 'w')
lines = ['line 1\n', 'line 2\n', 'line 3\n']
f.writelines(lines)
f.close()
Output-
line1
line2
line3
This will write the strings in the lines list to the file
myfile.txt. The \n characters are used to add newline
characters to the end of each string.
writelines method

Keep in mind that the writelines() method does not add


newline characters between the strings in the sequence.
If you want to add newlines between the strings, you can
use a loop to write each string separately:

f = open('myfile.txt', 'w')
lines = ['line 1', 'line 2', 'line 3']
for line in lines:
f.write(line + '\n')
f.close()
File Position

• In Python, the seek() and tell() functions are


used to work with file objects and their
positions within a file.
• These functions are part of the built-in io
module, which provides a consistent interface
for reading and writing to various file-like
objects, such as files, pipes, and in-memory
buffers.

43
seek() method
The seek() function allows you to move the current position
within a file to a specific point. The position is specified
in bytes, and you can move either forward or backward from
the current position. For example:
with open('file.txt', 'r') as f:
# Move to the 10th byte in the file
f.seek(10)
# Read the next 5 bytes
data = f.read(5)
seek() method
◼ The seek(offset, from) method changes the current file
position.
◼ The offset argument indicates the number of bytes to be
moved.
◼ from: Specifies the reference position:
◼ 0: Start of the file.
◼ 1: Current file pointer position.
◼ 2: End of the file.

◼ If from is set to 0, the beginning of the file is used as the


reference position. If it is set to 1, the current position is used
as the reference position. If it is set to 2 then the end of the
file would be taken as the reference position.
seek() method
Example 1: Using seek with from=0 (beginning of the file)

f = open('example.txt', 'w+')
f.write("Hello, world!")
f.seek(0) # Move pointer to the beginning of the file
print(f.read()) # Output: "Hello, world!"
f.close()
Example 2: Using seek with from=1 (current position)

f = open('example.txt', 'w+')
f.write("Hello, world!")
f.seek(5, 0) # Move to the 5th byte from the beginning
f.seek(2, 1) # Move 2 bytes forward from the current
position
print(f.read()) # Output: ", world!"
f.close()
seek() method
Example 3: Using seek with from=2 (end of the file)

f = open('example.txt', 'w+')
f.write("Hello, world!")
f.seek(-6, 2) # Move 6 bytes backward from the end
print(f.read()) # Output: "world!"
f.close()
tell() method
The tell() function returns the current position within the
file, in bytes. This can be useful for keeping track of your
location within the file or for seeking to a specific
position relative to the current position. For example:

with open('file.txt', 'r') as f:


# Read the first 10 bytes
data = f.read(10)
# Save the current positionss
current_position = f.tell()
print(current_position,end=“\n”)
# Seek to the saved position
f.seek(current_position)
Input- Hello, this is a sample text file for demonstration
purposes.
output= 10
Hello, thi
truncate() method
When you open a file in Python using the open function, you
can specify the mode in which you want to open the file. If
you specify the mode as 'w' or 'a', the file is opened in
write mode and you can write to the file. However, if you want
to truncate the file to a specific size, you can use the
truncate function.
Here is an example of how to use the truncate function:

with open('sample.txt', 'w') as f:


f.write('Hello World!')
f.truncate(5)
with open('sample.txt', 'r') as f:
print(f.read())

Output- Hello
Advantages of File Handling
•Versatility : File handling in Python allows you to perform a wide range
of operations, such as creating, reading, writing, appending, renaming,
and deleting files.

•Flexibility : File handling in Python is highly flexible, as it allows you to


work with different file types (e.g. text files, binary files, CSV files , etc.),
and to perform different operations on files (e.g. read, write, append, etc.).

•User – friendly : Python provides a user-friendly interface for file


handling, making it easy to create, read, and manipulate files.

•Cross-platform : Python file-handling functions work across different


platforms (e.g. Windows, Mac, Linux), allowing for seamless integration
and compatibility.
Disadvantages of File Handling
•Error-prone: File handling operations in Python can be prone to errors,
especially if the code is not carefully written or if there are issues with the
file system (e.g. file permissions, file locks, etc.).

•Security risks : File handling in Python can also pose security risks,
especially if the program accepts user input that can be used to access or
modify sensitive files on the system.

•Complexity : File handling in Python can be complex, especially when


working with more advanced file formats or operations. Careful attention
must be paid to the code to ensure that files are handled properly and
securely.

•Performance : File handling operations in Python can be slower than


other programming languages, especially when dealing with large files or
performing complex operations.
File…
◼ #opening a File
◼ f=open('demo.txt','w’) # Open in write mode
◼ f.write('hello world\nhow are you') # Write to the file
◼ f.close() # Close the file after writing
◼ #reading file
◼ f=open('demo.txt','r’) # Open in read mode
◼ print(f.read()) # Read the entire file content
◼ f.seek(0) # Repositioning cursor to the beginning of the file
◼ l=f.readlines() # Reading lines into a list
◼ print(l) # Print the list of lines
◼ f.seek(0) # Reset cursor to beginning
◼ for line in f.readlines(): print(line)
◼ ◼ f.seek(0)
◼ print(f.readline()) # Read and print the first line
◼ print(f.readline()) # Read and print the second line
◼ print(f.tell()) # Print the current position of the cursor
◼ #file object attribute
◼ print(f.name) # Print file name
◼ print(f.mode) # Print file mode
◼ print(f.closed) # Print if file is closed (should be False here)
◼ f.close() # Close the file
◼ with open('demo.txt','r') as f:
print(f.read(15)) # Read the first 15 characters
◼ ◼ #no need to close file opened using with

17

You might also like