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

PWP UNIT 6

The document covers File I/O handling and Exception handling in Python, detailing I/O operations such as printing to the screen and reading keyboard input. It explains file handling techniques including opening, writing, closing, renaming, and deleting files, as well as various built-in exceptions and how to handle them using try and except statements. Additionally, it discusses user-defined exceptions and the raise statement for custom error handling.

Uploaded by

phalketanu1205
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)
10 views

PWP UNIT 6

The document covers File I/O handling and Exception handling in Python, detailing I/O operations such as printing to the screen and reading keyboard input. It explains file handling techniques including opening, writing, closing, renaming, and deleting files, as well as various built-in exceptions and how to handle them using try and except statements. Additionally, it discusses user-defined exceptions and the raise statement for custom error handling.

Uploaded by

phalketanu1205
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/ 9

UNIT VI

File I/O Handling and Exception Handling

 I/O Operations :
o Printing to screen :
 The simplest way to produce output is using the print statement where
you can pass zero or more expressions separated by commas. This
function converts the expressions you pass into a string and writes the
result to standard output as follows.
 Example :
Print “Hello World”

o Reading Keyboard input :


 Python provides two built-in functions to read a line of text from
standard input, which by default comes from the keyboard. These
functions are –
 raw_input
 Input

The raw_input :
Function The raw_input([prompt]) function reads one line from
standard input and returns it as a string.
>>> str = raw_input("Enter your input: ")
Enter your input: mmpolytechnic
>>> print(str)
mmpolytechnic
>>>

The input Function :


The input([prompt]) function is equivalent to raw_input, except
that it assumes the input is a valid Python expression and returns
the evaluated result to you.
>>> str = input("Enter your name: ")
Enter your name: purva

Error: NameError: name 'purva' is not defined(“for string input”


instead of input use raw_input for accepting string value from user)

Mrs. K. G. Raut
>>> str = input("Enter your input: ")
Enter your input: 1
>>> print(str)

 File Handling :

o Opening file in different modes :


 The key function for working with files in Python is the open()
function.
 The open() function takes two parameters; filename, and mode.
 There are four different methods (modes) for opening a file:
 "r" - Read - Default value. Opens a file for reading, error if
the file does not exist
 "a" - Append - Opens a file for appending, creates the file if
it does not exist
 "w" - Write - Opens a file for writing, creates the file if it
does not exist
 "x" - Create - Creates the specified file, returns an error if
the file exists.
 In addition you can specify if the file should be handled as binary
or text mode
 "t" - Text - Default value. Text mode
 "b" - Binary - Binary mode (e.g. images)

Example :
1. f=open(“ABC.txt”)
2. f=open(“ABC.txt”,”r”)
3. f = open("demofile.txt", "r")
print(f.read())

o The write() Method


The write() method writes any string to an open file.
Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of
the string –

Mrs. K. G. Raut
1. f=open(“ABC”,”a”)
2. f.write(“Python is a programming language”)
3. f=open(“purva”,”r”)
4. print(f.read())

o Closing a file
Python automatically closes a file when the reference object of a file is
reassigned to another file. It is a good practice to use the close() method to
close a file.
f=open(“purva”,”r”)
print(f.read(1))
f.close()

o Renaming and deleting file


Python os module provides methods that help you perform file-
processing operations, such as renaming and deleting files. To use this
module you need to import it first and then call any related functions. The
rename() Method,

The rename()
method takes two arguments, the current filename and the new filename.

import os
os.rename(“TY”,”SY”)

The remove() Method


You can use the remove() method to delete files by supplying the name of the
file to be deleted as the argument.

import os
os.remove(“SY”)

 Exception Handling :
An exception can be defined as an abnormal condition in a program
resulting in the disruption in the flow of the program. Python provides us
with the way to handle the Exception so that the other part of the code

Mrs. K. G. Raut
can be executed without any disruption. However, if we do not handle the
exception, the interpreter doesn't execute all the code that exists after that.

 Different types of exceptions in python:

In Python, there are several built-in exceptions that can be raised when an
error occurs during the execution of a program. Here are some of the most
common types of exceptions in Python:
 SyntaxError: This exception is raised when the interpreter encounters a
syntax error in the code, such as a misspelled keyword, a missing colon, or
an unbalanced parenthesis.
 TypeError: This exception is raised when an operation or function is
applied to an object of the wrong type, such as adding a string to an integer.
 NameError: This exception is raised when a variable or function name is
not found in the current scope.
 IndexError: This exception is raised when an index is out of range for a
list, tuple, or other sequence types.
 KeyError: This exception is raised when a key is not found in a dictionary.
 ValueError: This exception is raised when a function or method is called
with an invalid argument or input, such as trying to convert a string to an
integer when the string does not represent a valid integer.
 AttributeError: This exception is raised when an attribute or method is
not found on an object, such as trying to access a non-existent attribute of a
class instance.
 IOError: This exception is raised when an I/O operation, such as reading
or writing a file, fails due to an input/output error.
 ZeroDivisionError: This exception is raised when an attempt is made to
divide a number by zero.
 ImportError: This exception is raised when an import statement fails to
find or load a module.

Mrs. K. G. Raut
 Try and Except Statement – Catching Exceptions

Try and except statements are used to catch and handle exceptions in Python.
Statements that can raise exceptions are kept inside the try clause and the
statements that handle the exception are written inside except clause.
In Python, exceptions can be handled using a try statement. A try block
consisting of one or more statements is used by programmers to partition code
that might be affected by an exception.

 A critical operation which can raise exception is placed inside the try
clause and the code that handles exception is written in except clause.
 The associated except blocks are used to handle any resulting exceptions
thrown in the try block. That is we want the try block to succeed and if it
does not succeed, we want to control to pass to the catch block.
 If any statement within the try block throws an exception, control
immediately shifts to the catch block. If no exception is thrown in the try
block, the catch block is skipped.
 There can be one or more except blocks. Multiple except blocks with
different exception names can be chained together.
 The except blocks are evaluated from top to bottom in the code, but only
one except block is executed for each exception that is thrown.
 The first except block that specifies the exact exception name of the
thrown exception is executed. If no except block specifies a matching
exception name then an except block that does not have an exception
name is selected, if one is present in the code.
 For handling exception in Python, the exception handler block needs to
be written which consists of set of statements that need to be executed
according to raised exception. There are three blocks that are used in the
exception handling process, namely, try, except and finally.

1. try Block:
A set of statements that may cause error during runtime are
to be written in the try block.

2. except Block:
It is written to display the execution details to the user when
certain exception occurs in the program. The except block executed
only when a certain type as exception occurs in the execution of
Mrs. K. G. Raut
statements written in the try block.

3. else block:
If no exception was raised in the try block, this block is
executed. It's useful for code that should run only if everything went
smoothly.

4. finally Block:
This is the last block written while writing an exception handler in
the program which indicates the set of statements that many use to
clean up to resources used by the program.

Syntax:
try:
D the operations here
......................
except Exception1:
If there is Exception1, then execute this block.
except Exception2:
If there is Exception2, then execute this block.
......................
else:
If there is no exception then execute this block.

Example 1 : For try-except clause/statement.


try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully")
fh.close()

Example 2 :
try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
Mrs. K. G. Raut
print("You can't divide by zero.")
except ValueError:
print("Please enter a valid number.")
else:
print(f"Result is {result}")
finally:
print("Program completed.")

 Raise Statement :
 The raise keyword is used to raise an exception.
 You can define what kind of error to raise, and the text to print to
the user.
o Example :
try:
age = int(input("Enter the age: "))
if age < 18:
raise ValueError("Age must be 18 or older.")
else:
print("The age is valid.")
except ValueError as e:
print(f"Invalid input: {e}")

Mrs. K. G. Raut
Except ValueError:
Print(“The age is not valid”)

Output :
Enter the Age ? 2
The age is not valid

 User Defined Exceptions :

Step 1 : Create user defined Exception class exception and inherit from an in-
built exception class.

Class YOurException(Exception):

Step 2 : Raising Exception

raise YourException ("something went wronh”)


For testing inside the try block , we are raising an exception using
keyword “Raise”

It create the intance of the exception class YourException.

Step 3 : Catching Exception


Now you have to catch the user defined exception using except block.

Step 4 : Write a program for user defined exception in python.

Example :
a=5
b=0
try :
k=int(input(“enter e number”))
print(k)

Mrs. K. G. Raut
print(“ file open “)
print(a/b)
except ZeroDivisionError as e :
print(“you cannot divide a number by zero”,e)
except ValueError as e :
print(“Invalid Input”)
except Exception :
print(“something went wrong”)
Finally :
Print(“file Closed”)

Mrs. K. G. Raut

You might also like