Chapter 6
Chapter 6
EXCEPTION HANDLING
I/O OPERATIONS
• 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 −
1. input(prompt)
2. input()
The input(prompt) Function :
The input([prompt]) function allows user input. It takes one argument. The
syntax is as follows:
Syntax: input(prompt)
Example:
x = input("Enter your name: ")
print(‘Hello ’ + x)
The input() Function:
The input() function always evaluate the input provided by user and
return same type data. The syntax is as follows:
Syntax: x=input()
Example:
x=int(input())
print(type(x))
• 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 –
The syntax is
Print(object(s),separator=separator,end=end,file=file,flush=flush)
Parameter values:
file = open(‘XYZ.txt','w')
file.write("This is the write command")
file.write("It allows us to write in a particular file")
file.close()
USE OF STANDARD LIBRARY FUNCTION
• raw_input(): The raw_input([prompt]) function reads one line from
standard input and returns it as a string (removing the trailing newline).
str = raw_input("Enter your input: ")
print("Received input is : ", str)
• input(): 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 input: ")
print("Received input is : ", str)
• open(): Before you can read or write a file, you have to open it using
Python's built-in open() function. This function creates a file object, which
would be utilized to call other support methods associated with it.
file object = open(file_name [, access_mode][, buffering])
• close(): The close() method of a file object flushes any unwritten
information and closes the file object, after which no more writing can be
done. 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.
file = open(“XYZ.txt", ‘w’)
print("Name of the file: ", XYZ.name)
# Close opend file
XYZ.close()
• write(): The write() method writes any string to an open file. It is important to
note that 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.
abc = open(“pqr.txt", "wb")
abc.write( "Python is a great language.\nYeah its great!!\n")
# Close opend file
abc.close()
• read(): The read() method reads a string from an open file. It is important to
note that Python strings can have binary data. apart from text data.
abc= open(“pqr.txt", "r+")
str = abc.read(10);
print("Read String is : ", str)
# Close opend file
abc.close()
• tell() method tells you the current position within the file; in other words, the next
read or write will occur at that many bytes from the beginning of the file.
• seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the
reference position from where the bytes are to be moved.
• rename() method takes two arguments, the current filename and the new filename.
• remove() method to delete files by supplying the name of the file to be deleted as
the argument.
• mkdir() method of the os module to create directories in the current directory.
• chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current
directory.
• getcwd() method displays the current working directory.
• rmdir() method deletes the directory, which is passed as an argument in the
method. Before removing a directory, all the contents in it should be removed.
RENAMING AND DELETING FILES
• 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 you can call any related functions.
rename(): rename() method takes two arguments, the current filename and
the new filename.
import os
# Rename a file from test1.txt to test2.txt
os.rename( "test1.txt", "test2.txt" )
remove(): remove() method to delete files by supplying the name of the file
to be deleted as the argument.
import os
# Delete file test2.txt
os.remove("text2.txt")
DIRECTORIES IN PYTHON
• All files are contained within various directories, and Python has no problem handling these
too. The os module has several methods that help you create, remove, and change
directories.
mkdir(): The mkdir() method of the os module to create directories in the current
directory. You need to supply an argument to this method which contains the name of the
directory to be created.
import os
# Create a directory "test"
os.mkdir("test")
chdir():The chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory.
import os
# Changing a directory to "/home/newdir"
os.chdir("/home/newdir")
getcwd(): The getcwd() method displays the current working directory.
import os
# This would give location of the current directory
os.getcwd()
rmdir(): The rmdir() method deletes the directory, which is passed as an
argument in the method. Before removing a directory, all the contents in it
should be removed.
import os
# This would remove "/tmp/test" directory.
os.rmdir( "/tmp/test" )
FILE AND DIRECTORY RELATED STANDARD
FUNCTIONS
• https://www.tutorialspoint.com/python/file_methods.htm
• https://www.tutorialspoint.com/python/os_file_methods.htm
EXCEPTION HANDLING
• Error in Python can be of two types i.e. Syntax errors and Exceptions.
• Syntax Errors are the problems in a program due to which the program will
stop the execution.
• This error is caused by the wrong syntax in the code.
• It leads to the termination of the program.
amount = 10000
if(amount > 2999)
print("You are eligible to purchase order")
• Exceptions are raised when some internal events occur which changes the
normal flow of the program.
• Exceptions are raised when the program is syntactically correct, but the code
resulted in an error.
• This error does not stop the execution of the program, however, it changes
the normal flow of the program.
marks = 10000
# perform division with 0
a = marks / 0
print(a)
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.
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error since there are only 3 elements in array
print ("Fourth element = %d" %(a[3]))
except:
print ("An error occurred")
CATCHING SPECIFIC EXCEPTION
• A try statement can have more than one except clause, to specify handlers for
different exceptions. Please note that at most one handler will be executed.
try:
# statement(s)
except IndexError:
# statement(s)
except ValueError:
# statement(s)
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print("Value of b = ", b)
try:
fun(3)
fun(5)
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")
TRY WITH ELSE CLAUSE
• Use the else clause on the try-except block which must be present after all the
except clauses.
• The code enters the else block only if the try clause does not raise an exception.
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
RAISING EXCEPTION