Unit 3
Unit 3
Unit-3
Basic input /output and working with
Files, Exceptions handling using
Python
Outline
Looping
x=float(input("your input:"))
your input:2.54
print(x+100) #output: 102.54
Basic IO operations in Python
Before we can read or write a file, we have to open it using Python's built-in open() function.
Syntax: fileobject = open(filename [, accessmode][, buffering])
filename is a name of a file we want to open.
accessmode is determines the mode in which file has to be opened (list of possible values given below)
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).
M Description M Description (create file if not exist) M Description
r Read only (default) w Write only Opens file to append, if file
a
not exist will create it for write
rb Read only in binary format wb Write only in binary format
Append in binary format, if file
r+ Read and Write both w+ Read and Write both ab
not exist will create it for write
Read and Write both in Read and Write both in Append, if file not exist it will
rb+ wb+ a+
binary format binary format create for read & write both
Read and Write both in binary
ab+
format
Example : Read file in Python
read(size) will read specified bytes from the file, if we don’t specify size it will return whole file.
readfile.py college.txt
1 f = open('college.txt') Text output: ?
2 data = f.read()
3 print(data)
We suppose to close the file once we are done using the file in the Python using close()
method.
closefile.py
1 f = open('college.txt')
2 data = f.read()
3 print(data)
4 f.close()
Handling errors using “with” keyword
It is possible that we may have typo in the filename or file we specified is moved/deleted, in
such cases there will be an error while running the file.
NB: typo is a python package to simulate typographical errors in English language.
To handle such situations we can use new syntax of opening the file using with keyword.
fileusingwith.py
1 with open('college.txt') as f :
2 data = f.read()
3 print(data)
When we open file using with we need not to close the file.
NB: in order to open any strings that are composition of any character, use the encoding when
you open the file.
fo=open('college.txt’, mode=‘r’, encoding=‘utf-8’) or
with open('college.txt’, mode=‘r’, encoding=‘utf-8’) as f :
Read(), tell(), seek(), write() methods
The read() method can take integer argument. Ex: data = f.read(5)
The number indicates the number of bytes to be read from the opened file.
The 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.
The seek(offset[, from]) method changes the current position of the file pointer within a file.
The file pointer is a marker that indicates the current position in the file, and it is used to read or
write data from that point.
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.
If from is set to 0, the beginning of the file is used as the reference position. (default)
If from is set to 1, the current position is used as the reference position. (i.e., seek relative to the current
position)
If from is set to 2, then the end of the file would be taken as the reference position. (i.e., seek relative to
the file's end)
Read(), tell(), seek(), write() methods
example.py
# Open a file [first create a file that contains some string of lines
fo = open( “mytext.txt", "r+")
str = fo.read(10)
print ("Read String is : ", str)
# Check current position.
position = fo.tell()
print ("Current file position : ", position)
# Re-position pointer at the beginning once again
position = fo.seek(0, 0)
str = fo.read(10)
print ("Again read String is : ", str)
# Close opened file
fo.close() Output:
Read String is : Python is
Current file position : 10
Again read String is : Python is
Read(), tell(), seek(), write() methods
When using from value 1 in seek(), the method may throw an io.UnsupportedOperation
exception if the file is not opened in binary mode.
Let the file tt.txt contains the following string.
This is python file opening.
And then, we will see it.
Example-2.py
1 fi=open("tt.txt",'r+')
2 print(fi.read()) Output:
3 fi.seek(15) This is python file opening.
4 #po=fi.seek(15,1)# error can't do nonzero cur-relative seeks And then, we will see it.
5 #po=fi.seek(15,0) # no error
6 po=fi.seek(0,1) # offset value is 15 which takes from line 3 current position: 15
7 #po=fi.seek(18,0)# offset value is 18 and prints ‘e opening…..’ file opening.
8 print("current position: ",po) And then, we will see it.
9 print(fi.read())
10 #print(fi.read(po)) NB: Try other output yourself by
changing parameters.
11 fi.close()
Read(), tell(), seek(), write() methods
If you open your file in binary mode, you can use the following rules as you want.
The from value = SEEK_SET or 0 is the default value that seeks from the beginning of the file.
Here the offset should be zero or positive.
The from value = SEEK_CUR or 1 is its value denotes the current file position. The offset can be
either positive or negative.
The from value = SEEK_END or 2 is value that indicates the pointer is at the end of the file.
Here the offset is usually negative.
NB: you can use os.SEEK_SET as 0, os.SEEK_CUR as 1, and os.SEEK_END as 2 by using import os
Example.py
1 Import os
2 fi=open("tt.txt",'rb+')
3 print(fi.read())
4 fi.seek(15, os.SEEK_SET) # Setting file pointer at the 15th position
5 po=fi.seek(18, os.SEEK_CUR) #Move file pointer 18 characters ahead from the current position
6 fo=fi.seek(-10, os.SEEK_END) # Moving file pointer back 10 chars from the end of file
7 fi.close()
Read(), tell(), seek(), write() methods
Opening file with binary mode and using seek()
Let the file tt.txt contains the following string.
This is python file opening.
And then, we will see it.
Example-3.py
1 fi=open("tt.txt",'rb+') Output:
2 print(fi.read()) b'This is python file opening.\r\nAnd then, we
3 fi.seek(15) will see it.\r\n\r\n'
4 po=fi.seek(18,1) current position: 33
5 print("current position: ",po) b' then, we will see it.\r\n\r\n'
6 dt=fi.read()
7 print(dt)
8 fi.close()
Read(), tell(), seek(), write() methods
Opening file with binary mode and using seek()
In order to return the binary mode to normal string, use the decode method.
Example-4.py
1 fi=open("tt.txt",'rb+')
Output:
2 print(fi.read().decode("utf-8"))
This is python file opening.
3 fi.seek(15)
And then, we will see it.
4 po=fi.seek(18,1)
5 print("current position: ",po)
current position: 33
6 dt=fi.read().decode("utf-8")
then, we will see it.
7 print(dt)
8 fi.close()
Read(), tell(), seek(), write() methods
Opening file with binary mode and using seek()
To write a string in specified position of file, use as follows:
Example-5.py
1 fi=open("tt.txt",'rb+')
2 print(fi.read().decode("utf-8"))
3 po=fi.seek(10) Output:
4 po=fi.seek(11,1) This is python file opening.
5 fi.write(b"NEW INSERTION")
6 print("current position: ",po) And then, we will see it.
7 dt=fi.read().decode("utf-8") current position: 21
8 print(dt) then, we will see it.
9 fi.close()
+++After the file modification.+++
10
11 print("+++After the file modification.+++") This is python file oNEW INSERTIONthen,
12 f=open("tt.txt",'rb+') we will see it.
13 dt=f.read().decode("utf-8")
14 print(dt)
15 f.close()
Write and append file in Python
write() method will write the specified data to the file. readdemo.py
1 with open('college.txt','a') as f :
2 f.write('Hello world')
If we open file with ‘w’ mode it will overwrite the data to the existing file or will create new file
if file does not exists.
If we open file with ‘a’ mode it will append the data at the end of the existing file or will create
new file if file does not exists. Or you can write new input at specified place of file as follow:
write()Example.py
1 fo = open("tt.txt", "r+")
2 print ("Name of the file: ", fo.name)
3 str = "This is new line"
4
fo.seek(0,2) # make file pointer at EOF to write new text at the end of the file
5
6 line = fo.write(str)
7 fo.seek(0,0) # Now read complete file from beginning.
8 for index in range(5): # 5 is # of line
9 line = next(fo)
10 print ("Line No %d - %s" % (index, line))
11 fo.close()
Reading CSV files without any library functions
A comma-separated values file is a delimited text file that uses a comma to separate values.
Each line of is a data record, each record consists of many fields, separated by commas.
Example : Book1.csv readCSV.py
studentname,enrollment,cpi 1 1with open('Book1.csv') as f :
abcd,123456,8.5 2 2 rows = f.readlines()
bcde,456789,2.5 3 3 isFirstLine = True
cdef,321654,7.6 4 4 for r in rows :
5 5 if isFirstLine :
6 6 isFirstLine = False
We can use Microsoft Excel to access 7 7 continue
8 cols = r.split(',')
CSV files. 9 print('Student Name = ', cols[0], end=" ")
10 print('\tEn. No. = ', cols[1], end=" ")
11 print('\tCPI = \t', cols[2])
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.
Renaming file name:
Syntax: os.rename( current_file_name, new_file_name)
Removing file :
Syntax: os. remove( file_name)
renameAndRemoveExample.py
1 import os
2 # Rename a file from test1.txt to test2.txt
3 os. rename( "test1.txt", "test2.txt" )
4
# Delete file test2.txt
5
6 os. remove( "text2.txt")
Directories in Python
The os module has several methods that help you create, remove, and change
directories.
The mkdir() Method: used to create directories in the current directory.
Syntax: os.mkdir("newdir")
The chdir() Method: used to change the current directory location
Syntax: os.chdir("newdir" )
The getcwd() Method: displays the current createChangeDirectoryExample.py
working directory. 1 import os
Syntax: os.getcwd() 2 # Create a directory "test"
3 os.mkdir("test")
The rmdir() Method: deletes the directory. 4 # Changing a directory to ".\\Desktop\\newdir"
5
Before removing a directory, all the contents 6 os.chdir(".\\Desktop\\newdir")
# give location of current directory
in it should be removed. 7
8 os.getcwd()
Syntax: os.rmdir('dirname’) 9 # would remove "/tmp/test“ directory
10 os.rmdir("/tmp/test")
File & Directory Related Methods
There are important sources, which provide a wide range of utility methods to handle
and manipulate files & directories on Windows and Unix operating systems.
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
File methods: A file object is created using open function and here is a list of functions which can
be called on this object.
Methods Descriptions
file.flush() Flush the internal buffer, like stdio's fflush. The word flush means clear.
file.fileno() Returns the integer file descriptor that is used by the underlying implementation to request I/O
operations from the operating system.
file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
next(file) Returns the next line from the file each time it is being called
file.truncate([size]) Truncates the file's size. If the optional size argument is present, the file is truncated to (at
most) that size.
file.writelines(sequ Writes a sequence of strings to the file. The sequence can be any iterable object producing
strings, typically a list of strings.
ence)
File & Directory Related Methods
flushExample.py
1 #use it in all open modes (r,a,...)
2 fi=open("tt.txt",'r')
3
print("text before flush.\n",fi.read())
4
5 fi.flush()
6 print("text after flush.\n",fi.read())
7 fi.close()
file.isatty(): tty(-like) device means a device that acts like a teletype, for example a virtual
console/ terminal. tty stand for TeleTYpewriter.
isattyExample.py
1 fo = open("tt.txt", "wb") Output:
2 print ("Name of the file: ", fo.name) Name of the file: tt.txt
3 ret = fo.isatty() Return value : False
4 print ("Return value : ", ret)
5 fo.close()
File & Directory Related Methods
File object in Python 3 does not support next() method. (i.e. you cannot write like: fo.next(fo))
Python 3 has a built-in function next() which retrieves the next item from the iterator by calling
its __next__() method.
If default is given, it is returned if the iterator is exhausted, otherwise StopIteration is raised.
Let tt.txt has the contents: C++
Java
Python Output:
C# Name of the file: tt.txt
PHP Line No: 0 - C++
Next()Example.py
1 fo = open("tt.txt", "r") Line No: 1 - Java
2 print ("Name of the file: ", fo.name)
3 Line No: 2 - Python
for index in range(5):
4
5
line = next(fo)
6 print ("Line No: %d - %s" % (index, line)) Line No: 3 - C#
7 fo.close()
Line No: 4 - PHP
File & Directory Related Methods
The method truncate() truncates the file's size.
If the optional size argument is present, the file is truncated to (at most) that size.
The size defaults to the current position.
The current file position is not changed.
Note that if a specified size exceeds the file's current size, the result is platform-dependent.
Note: This method will not work in case the file is opened in read-only mode.
truncate()Example.py
1 fo = open("tt.txt", "r+")
2 print ("Name of the file: ", fo.name)
3
line = fo.readline()#reads 1 line only
4
5
print ("Read Line: %s" % (line))
6 fo.truncate(5) #cut/minimize your file content to 5 characters/bytes
7 line = fo.readlines() #reads all lines
8 #for l in line1:
9 print ("Read Line: %s" % (line))
10 fo.close()
File & Directory Related Methods
The method writelines() writes a sequence of strings to the file.
The sequence can be any iterable object producing strings, typically a list of strings.
There is no return value. C++
Let tt.txt has the contents: Java
writeline()Example.py Python
1 fo = open("tt.txt", "r+") C#
2 print ("Name of the file: ", fo.name) PHP
3 seq = ["\nPerl", "\nVisual basic"]
4 #seq = "\nPerl \nVisual basic" # you can use both
5
# Write sequence of lines at the end of the file.
6
7
fo.seek(0,2)
8 line = fo.writelines(seq)
9 # Now read complete file from beginning.
10 fo.seek(0,0)
11 for index in range(7): # 7 is number of line
12 line = next(fo)
13 print ("Line No %d - %s" % (index, line))
14
fo.close()
OS File/Directory Methods
The os module provides a big range of useful methods to manipulate files and directories.
Methods Descriptions
os.access(path, mode) Use the real uid/gid (user id/group id) to test for access to path.
os.chflags(path, flags) Set the flags of path to the numeric flags.
os.chmod(path, mode) Change the mode of path to the numeric mode.
os.chown(path, uid, gid) Change the owner and group id of path to the numeric uid and gid.
os.chroot(path) Change the root directory of the current process to path.
os.close(fd) Close file descriptor fd.
os.closerange(fd_low, fd_high) Close all file descriptors from fd_low (inclusive) to fd_high (exclusive), ignoring errors.
os.dup(fd) Return a duplicate of file descriptor fd.
os.dup2(fd, fd2) Duplicate file descriptor fd to fd2, closing the latter first if necessary.
os.fpathconf(fd, name) Return system configuration information relevant to an open file. Name specifies the
configuration value to retrieve.
os.open(file, flags[, mode]) Open file and set various flags according to flags and possibly its mode according to mode.
os.pipe(r, w) Create a pipe. Return a pair of file descriptors (r, w) usable for reading and writing,
respectively.
OS File/Directory Methods
os.access(path, mode) : uses the real uid/gid to test for access to path.
Most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid
environment to test if the invoking user has the specified access to path.
It returns True if access is allowed, False if not.
path - This is the path which would be tested for existence or any access.
mode - This should be F_OK to test the existence of path, or it can be the inclusive OR of one or
more of R_OK, W_OK, and X_OK to test permissions.
os.F_OK: Value to pass as the mode parameter of access() to test the existence of path.
os.R_OK: Value to include in the mode parameter of access() to test the readability of path.
os.W_OK: Value to include in the mode parameter of access() to test the writability of path.
os.X_OK: Value to include in the mode parameter of access() to determine if path can be
executed.
OS File/Directory Methods
Access()Example.py
1 import os
2 # Assuming tt.txt exists
3
# And it has read/write permissions.
4
5
print ("F_OK - return value %s"% os.access("tt.txt", os.F_OK))
6 print ("R_OK - return value %s"% os.access("tt.txt", os.R_OK))
7 print ("W_OK - return value %s"% os.access("tt.txt", os.W_OK))
8 print ("X_OK - return value %s"% os.access("tt.txt", os.X_OK))
Output:
F_OK - return value True
R_OK - return value True
W_OK - return value True
X_OK - return value True
OS File/Directory Methods
The method chflags() sets the flags of path to the numeric flags.
The flags may take a combination (bitwise OR) of the various values described below.
Note: This method is available Python version 2.6 onwards. Most of the flags can be changed by super-
user only.
path - This is a complete path of the directory to be changed to a new location.
flags - The flags specified are formed by OR'ing the following values os.UF_NODUMP: Do not dump the
file. NB: chflags() is available on UNIX platforms only.
os.UF_IMMUTABLE: The file may not be changed.
os.UF_APPEND: The file may only be appended to.
os.UF_NOUNLINK: The file may not be renamed or deleted.
os.UF_OPAQUE: The directory is opaque when viewed through a union stack.
os.SF_ARCHIVED: The file may be archived.
chflags()Example.py
os.SF_IMMUTABLE: The file may not be changed.
import os
os.SF_APPEND: The file may only be appended to. flags = os.SF_NOUNLINK
os.SF_NOUNLINK: The file may not be renamed or deleted. retval = os.chflags("tt.txt", flags)
os.SF_SNAPSHOT: The file is a snapshot file. print("Return Value: %s" % retval)
OS File/Directory Methods
The method chmod() changes the mode of path to the passed numeric mode.
i.e., it used to change the permissions of a file or directory.
The mode may take one of the following values or bitwise ORed combinations of them :-
stat.S_ISUID: Set user ID on execution.
stat.S_ISGID: Set group ID on execution.
stat.S_ENFMT: Record locking enforced.
stat.S_ISVTX: Save text image after execution.
stat.S_IREAD: Read by owner.
stat.S_IWRITE: Write by owner.
stat.S_IEXEC: Execute by owner.
stat.S_IRWXU: Read, write, and execute by owner.
stat.S_IRUSR: Read by owner.
stat.S_IWUSR: Write by owner.
stat.S_IXUSR: Execute by owner.
OS File/Directory Methods
stat.S_IRWXG: Read, write, and execute by group.
stat.S_IRGRP: Read by group.
stat.S_IWGRP: Write by group.
stat.S_IXGRP: Execute by group.
stat.S_IRWXO: Read, write, and execute by others.
stat.S_IROTH: Read by others.
stat.S_IWOTH: Write by others.
stat.S_IXOTH: Execute by others.
chmod()Example.py
chmod()Example-2.py
1 import os, stat 1 import os, stat
2 #Set a file execute by the group.
3
2 # Set given file read by the owner.
os.chmod("./tt.txt", stat.S_IXGRP) 3
4 os.chmod("./tt.txt", stat.S_IREAD)
# Set a file write by others. 4
5 print("File can be read only by owner.")
os.chmod("./tt.txt", stat.S_IWOTH) 5
6 # Set given file read by others.
print ("Changed mode successfully!") 6
7
7 os.chmod("./tt.txt", stat.S_IROTH)
8 print(“Now, file access changed, can be read by others.")
OS File/Directory Methods
The method chown() changes the owner and group id of path to the numeric uid and gid.
To leave one of the ids unchanged, set it to -1.To set ownership, you would need super
user privilege.
Parameters
path - This is the path for which owner id and group id need to be setup.
uid - This is Owner ID to be set for the file.
gid - This is Group ID to be set for the file.
The method chroot() changes the root directory of the current process to the given path.
To use this method, you would need super user privilege.
Chown() and chroot() available only on UNIX platforms
chroot()Example.py
chown()Example.py
1 import os
1
2
import os 2 # To set the current root path to /tmp/user
3 os.chroot("/tmp/usr")
3 os.chown("tt.txt", 100, -1) 4
4 print ("Changed ownership successfully!") print ("Changed root path successfully!")
OS File/Directory Methods
The method close(fd) closes the file descriptor fd . So that it no longer refers to any file or
other resource and may be reused.
Note: This function is intended for low-level I/O and must be applied to a file descriptor
as returned by os.open() or pipe().
os.close()Example.py
1 import os
2 fd = os.open ("tt.txt", os.O_RDWR|os.O_CREAT)
3 line="this is test" # Write one string
4
b=str.encode(line) # string needs to be converted byte object
5
os.write(fd,b)
6
7 os.close(fd)
8 print ("Closed ownership successfully!")
OS File/Directory Methods
The method closerange(fd_low, fd_high) closes all file descriptors from fd_low (inclusive) to
fd_high (exclusive), ignoring errors.
fd_low - This is the Lowest file descriptor to be closed.
fd_high - This is the Highest file descriptor to be closed.
This function is equivalent to:- for fd in xrange(fd_low, fd_high):
try:
os.close(fd)
except OSError:
pass
This method is introduced in Python version >= 2.6.
os.closerange()Example.py
1 import os, sys
2 fd = os.open("tt.txt", os.O_RDWR|os.O_CREAT)
3 line="this is test" # Write one string
4
b=str.encode(line) # string needs to be converted byte object
5
6 os.write(fd, b)
7 os.closerange( fd, fd) # Close a single opened file
8 print ("Closed all the files successfully!")
OS File/Directory Methods
The method dup(fd) returns a duplicate of file descriptor fd which can be used in place of
original descriptor.
fd - This is the original file descriptor.
This method returns a duplicate of file descriptor.
os.dup()Example.py
1 import os, sys
2 fd = os.open("tt.txt", os.O_RDWR|os.O_CREAT)
3 d_fd = os.dup(fd) # Get one duplicate file descriptor
4
print("d_fd value: ", d_fd) #prints d_fd value: 4
5
6 line="this is test" # Write one string using duplicate fd
7 b=str.encode(line) # string needs to be converted byte object
8 os.write(d_fd, b)
9 os.closerange(fd, fd) # Close opened files
10 print ("Closed all the files successfully!")
OS File/Directory Methods
The method dup2(fd, fd2) duplicates file descriptor fd to fd2, closing the latter first if
necessary.
The file descriptor will be duplicated to fd2 only if fd2 is available and duplicated file descriptor
is inheritable by default.
Inheritable file descriptor means if the parent process has a file descriptor 4 in use for a
particular file and the parent creates a child process then the child process will also have file
descriptor 4 in use for that same file.
fd - This is File descriptor to be duplicated.
fd2 - This is Duplicate file descriptor.
This method returns a duplicate of file descriptor.
Note: New file description would be assigned only when it is available.
In the next example given in next slide, 1000 would be assigned as a duplicate fd in case
when 1000 is available.
OS File/Directory Methods
The method dup2(fd, fd2)
dup2()Example.py
1 import os, sys
2 fd = os.open("tt.txt", os.O_RDWR|os.O_CREAT)
3 d_fd = os.dup(fd) # Get one duplicate file descriptor
4
line="this is test" # Write one string using duplicate fd
5
6 b=str.encode(line) # string needs to be converted byte object
7 os.write(d_fd, b)
8 fd2 = 1000 # Now duplicate this file descriptor as 1000
9 print("fd2 value: ",os.dup2(fd, fd2)) # prints fd2 value: 1000
10 os.lseek(fd2, 0, 0) # Now read this file from the beginning using fd2.
11 line = os.read(fd2, 100)
12 str=line.decode() # no need of argument since 'encoding' must be str, not bytes
13
print ("Read String is : ", str)
14
15 os.closerange( fd, fd2) # Close opened files
16 print ("Closed all the files successfully!")
OS File/Directory Methods
The method fpathconf(fd, name) returns system configuration information relevant to an
open file.
This variable is very similar to Unix system call fpathconf() and accept the similar
arguments.
fd - is the file descriptor for which system configuration information is to be returned.
name - specifies the configuration value to retrieve; it may be a string, which is the name
of a defined system value; these names are specified in a number of standards (POSIX.1,
Unix 95, Unix 98, and others).
The names known to the host operating system are given in the os.pathconf_names
dictionary.
This method returns system configuration information relevant to an open file.
OS File/Directory Methods
The method fpathconf(fd, name)
fpathconf()Example.py
1 import os, sys
2 fd = os.open("tt.txt", os.O_RDWR|os.O_CREAT)
3
4
print ("%s" % os.pathconf_names)
5 # Now get maximum number of links to the file.
6 no = os.fpathconf(fd, 'PC_LINK_MAX')
7 print ("Maximum number of links to the file. :%d" % no)
8 # Now get maximum length of a filename
9
no = os.fpathconf(fd, 'PC_NAME_MAX')
10
11 print ("Maximum length of a filename :%d" % no)
12 os.closerange(fd, fd) # Close opened files
13 print ("Closed all the files successfully!")
1 def avg(marks):
2 assert len(marks) != 0,"List is empty."
3 return sum(marks)/len(marks)
4 mark2 = [55,88,78,90,79]
5 print("Average of mark2:",avg(mark2))
6 mark1 = []
7 print("Average of mark1:",avg(mark1))
Output:
ERROR!
Average of mark2: 78.0
Traceback (most recent call last):
File "<string>", line 7, in <module>
File "<string>", line 2, in avg
AssertionError: List is empty.
Exceptions Handling in python
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
try:
Handling an Exception Syntax: 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.
Exceptions Handling in python
Con…
ExceptioonExample.py
1 try:
2 fh = open("testfile.txt", "w")
3 fh. write("This is my test file for exception handling!!")
4 except IOError:
5 print ("Error: can\'t find file or read data")
6 else:
7 print ( "Written content in the file successfully")
8 fh.close()
if the file exists and have a permission:
Output:
Written content in the file successfully
Exceptions Handling in python
Example-2: This example tries to open a file where you do not have the write permission, so it
raises.
ExceptioonExample-2.py
1 try:
2 fh = open("testfile", "r")
3 fh. write("This is my test file for exception handling!!")
4 except IOError:
5 print ( "Error: can\'t find file or read data" )
6 else:
7 print ( "Written content in the file successfully")
Output:
Error: can't find file or read data
Exceptions Handling in python
The except Clause with No Exceptions
You can also use the except statement with no exceptions defined as follows:
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.
This kind of a try-except statement catches all the exceptions that occur.
Using this kind of try-except statement is not considered a good programming practice though,
because it catches all exceptions but does not make the programmer identify the root cause of
the problem that may occur.
Exceptions Handling in python
The except Clause with 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.
Exceptions Handling in python
The try-finally Clause:
Syntax: try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
NB: When an exception is thrown in the try block, the execution immediately passes to the finally block.
After all the statements in the finally block are executed, the exception is raised again and is handled in
the except statements if present in the next higher layer of the try-except statement.
Exceptions Handling in python
Exception’s Argument: An exception can have an argument, which is a value that gives
additional information about the problem.
The contents of the argument vary by exception.
You capture an exception's argument by supplying a variable in the except clause as follows:
try:
You do your operations here
......................
except ExceptionType as Argument:
You can print value of Argument here
Example:
def temp_convert(var): Output:
try: The argument is not number.
return int(var) # int indicates return type of data
except ValueError as my_Argument: invalid literal for int() with
print("The argument is not number\n", my_Argument) base 10: 'xx'
# Call above function here.
temp_convert("xx")