[go: up one dir, main page]

0% found this document useful (0 votes)
94 views30 pages

(Pick The Date) : PPG Institute of Technology

The document discusses files, modules, and packages in Python. It covers opening and closing files, reading and writing to files, appending to files, and renaming/deleting files. It also covers directories in Python, including making new directories, getting the current directory, changing directories, and removing directories. Key methods discussed for files include open(), close(), read(), readline(), readlines(), and write(). For directories, methods include mkdir(), getcwd(), and remove(). Examples are provided for many of these file and directory methods in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views30 pages

(Pick The Date) : PPG Institute of Technology

The document discusses files, modules, and packages in Python. It covers opening and closing files, reading and writing to files, appending to files, and renaming/deleting files. It also covers directories in Python, including making new directories, getting the current directory, changing directories, and removing directories. Key methods discussed for files include open(), close(), read(), readline(), readlines(), and write(). For directories, methods include mkdir(), getcwd(), and remove(). Examples are provided for many of these file and directory methods in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 30

[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

UNIT V FILES, MODULES, PACKAGES


Files and exception: text files, reading and writing files, format operator; command line
arguments, errors and exceptions, handling exceptions, modules, packages; Illustrative
programs: word count, copy file.

5.1 FILES
 A file represents a sequence of bytes on the disk where a group of related data is
stored. 
 File is created for permanent storage of data.

5.1.1 Categories of files:


 Text file – contains textual information
 Binary file- contains binary data which is only readable by computer

5.1.2 File operations


 Opening a file
 Reading from a file
 Writing to a file
 Closing a file

5.2 OPENING A FILE


 We have to open a file before reading/writing file 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.
 Syntax

file object = open(file_name access_mode, buffering])

 Here are parameter details −


 file_name − The file_name argument is a string value that contains the name of
the file that we want to access.
 access_mode − The access_mode determines the mode in which the file has to
be opened, i.e., read, write, append, etc.

PPG INSTITUTE OF TECHNOLOGY Page 1


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 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.

5.2.1 Different Modes of Opening a File

S.No. Mode & Description

r
1 Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.

rb
2 Opens a file for reading only in binary format. The file pointer is placed at the
beginning of the file. This is the default mode.

r+
3 Opens a file for both reading and writing. The file pointer placed at the beginning
of the file.

rb+
4 Opens a file for both reading and writing in binary format. The file pointer placed
at the beginning of the file.

w
5 Opens a file for writing only. Overwrites the file if the file exists. Otherwise,
creates a new file for writing.

wb
6 Opens a file for writing only in binary format. Overwrites the file if the file exists.
Otherwise, creates a new file for writing.

w+
7 Opens a file for both writing and reading. Overwrites the existing file if the file
exists. Otherwise, creates a new file for reading and writing.

wb+
8 Opens a file for both writing and reading in binary format. Overwrites the existing
file if the file exists. Otherwise, creates a new file for reading and writing.

9 a

PPG INSTITUTE OF TECHNOLOGY Page 2


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Opens a file for appending. The file pointer is at the end of the file if the file exists.
Otherwise, it creates a new file for writing.

ab
10 Opens a file for appending in binary format. The file pointer is at the end of the file
if the file exists. Otherwise, it creates a new file for writing.

a+
11 Opens a file for both appending and reading. The file pointer is at the end of the
file if the file exists. Otherwise, it creates a new file for reading and writing.

ab+
Opens a file for both appending and reading in binary format. The file pointer is at
12
the end of the file if the file exists. Otherwise, it creates a new file for reading and
writing.

5.2.2 File Object Attributes


 Once a file is opened and we can get various information related to that file by using
file object.
 Here is a list of all the attributes related to a file object −

S.No. Attribute & Description

file.closed
1
Returns true if file is closed, false otherwise.

file.mode
2
Returns access mode with which file was opened.

PPG INSTITUTE OF TECHNOLOGY Page 3


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

file.name
3
Returns name of the file.

5.2.3 Example

fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("Closed or not : ", fo.closed)
print ("Opening mode : ", fo.mode)
fo.close()

Output

Name of the file: foo.txt


Closed or not : False
Opening mode : wb

5.2.4 The close() Method


 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.
 Syntax
fileObject.close();

 Example
fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
fo.close()

 Output:

Name of the file: foo.txt

5.3 WRITING TO A FILE


 The write() method writes any string or sequence of bytes to an open file.

PPG INSTITUTE OF TECHNOLOGY Page 4


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 The write() method does not add a newline character ('\n') to the end of the string
 Syntax

fileObject.write(string);

 Example

fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()

 Output:
foo.txt

Python is a great language.


Yeah its great!!

5.4 READ FROM A FILE


 In order to read the content of a file, we need to open the file in read mode.
 Following are the various methods to read a text file in python.

5.4.1 read()
 It reads specified the specified number of characters from the file.
 If omitted it will read entire contents of the file.
 Syntax:
f.read(size)
Here size is optional and returns a data of specified size
 Program:
f=open(“new.txt”,’r’)
f.read(4)
 Input file: (new.txt)
Python programming
Interpreted
 Output:
‘Pyth’

PPG INSTITUTE OF TECHNOLOGY Page 5


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

5.4.2 readline()
 It is used to read individual lines of a file.
 It reads a file till the newline(\n) character is reached or end of file(EOF)
 Syntax:
f.readline(size)
Here size is optional and returns a data of specified size
 Program:
f=open(“new.txt”,’r’)
f.readline()
 Input file: (new.txt)
Python programming
Interpreted
 Output:
‘Python programming’

5.4.3 readlines()
 It is used to read list of lines on the entire file.
 Syntax:
f.readlines(size)
Here size is optional and returns a data of specified size
 Program:
f=open(“new.txt”,’r’)
f.readlines()
 Input file: (new.txt)
Python programming
Interpreted
 Output:
[‘Python programming\n’, ‘Interpreted\n’]

5.5 APPENDING DATA TO A FILE:


 In order to append a new text to the already existing file or to the new file, we have to
reopen the file in append mode ‘a’
 Syntax:
PPG INSTITUTE OF TECHNOLOGY Page 6
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

f.open(“filename”,’a’)
 Program:
f=open(“new.txt”,”a”)
f.write(“Easy to learn\n”)
f.close()
 Input file: (new.txt)
Python programming
Interpreted
 Output:
Python programming
Interpreted
Easy to learn

5.6 RENAMING AND DELETING A FILE


1. rename()
 It is used to rename an existing file by a new file name.
 Example:
import os
os.rename(“old.txt”,”new.txt”)
2. remove()
 It is used to delete an existing file.
 Example:
import os
os.remove(“new.txt”)

5.7 DIRECTORIES IN PYTHON


 A directory is a collection of files and directories.
 Python has the os module methods to perform the following operations:
 Making a new directory
 Get Current Directory
 Changing Directory
PPG INSTITUTE OF TECHNOLOGY Page 7
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Removing Directory from the file

 List Directories and files


S No Method & Description Syntax and Example
1 Making new directory Syntax
mkdir() - Creates a new directory os.mkdir(“new”)
Example
import os
os.mkdir(“new”)
2 Get Current Directory Syntax
getcwd() – Returns current os.getcwd()
working directory os.getcwdb()
getcwdb() – Returns current Example
working directory as byte objects >>>import os
>>>os. getcwd()
'C:\\Users\\Arthi\\AppData\\Local
\\Programs\\Python\\Python36-32'
>>>os.getcwdb()
b'C:\\Users\\Arthi\\AppData\\Local
\\Programs\\Python\\Python36-32'
3 Changing Directory Syntax:
chdir() – Changes the current os.chdir(“new”)
working directory Example:
Use either forward (/) or backward import os
(\) slash to separate path elements os.chdir(“/ex/python”)
4 Removing Directory from the Syntax:
file os.rmdir(“dirname”)
rmdir() – Deletes or removes Example:
directory import os
os.rmdir(“/test/python”)
5 List Directories and files Syntax:
listdir() – Lists all directories and os.listdir()
files inside a given directory Example:
>>>os.listdir()
['cmd.py', 'count.py']
PPG INSTITUTE OF TECHNOLOGY Page 8
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

5.8 File Methods

S.No. Methods & Description

file.close()
1
Close the file. A closed file cannot be read or written any more.

file.flush()
2
Flush the internal buffer of file object.

file.fileno()
3 Returns the integer file descriptor to request I/O operations from the operating
system.

file.isatty()
4
Returns True if the file is connected to interactive, else False.

next(file)
5
Returns the next line from the file each time it is being called.

file.read([size])
6 It reads specified the specified number of characters from the file
If omitted it will read entire contents of the file.

file.readline([size])
7 It is used to read individual lines of a file.
It reads a file till the newline(\n) character is reached or end of file(EOF)

8 file.readlines([sizehint])

PPG INSTITUTE OF TECHNOLOGY Page 9


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

It is used to read list of lines on the entire file.

file.seek(offset[, whence])
9
Sets the file's current position

file.tell()
10
Returns the file's current position

file.truncate([size])
11 Truncates the file's size. If the optional size argument is present, the file is
truncated to (at most) that size.

file.write(str)
12
Writes a string to the file.

file.writelines(sequence)
13 Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.

5.8.1 flush()
 The method flush() flushes the internal buffer of file objects.
 Python automatically flushes the files when closing them.
 Syntax

fileObject.flush()

 Example

fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
fo.flush()
fo.close()

 Output

Name of the file: foo.txt

5.8.2 fileno()
 The method fileno() returns the integer file descriptor which is used to request I/O
operations from the operating system.
PPG INSTITUTE OF TECHNOLOGY Page 10
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Syntax

fileObject.fileno()

 Example

fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
print ("File Descriptor: ", fo.fileno())
fo.close()

 Output

Name of the file: foo.txt


File Descriptor: 3

5.8.3 isatty() 
 The method isatty() returns True if the file is connected or associated with a terminal
device, else False.
 Syntax

fileObject.isatty()

 Example

fo = open("foo.txt", "wb")
print ("Name of the file: ", fo.name)
ret = fo.isatty()
print ("Return value : ", ret)
fo.close()

 Output

Name of the file: foo.txt


Return value : False

5.8.4 seek()
 The method seek() sets the file's current position at the offset.
 Syntax

PPG INSTITUTE OF TECHNOLOGY Page 11


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

fileObject.seek(offset, whence)

 Parameters
 offset − This is the position of the read/write pointer within the file.
 whence − This is optional and defaults to 0 which means absolute file
positioning, other values are 1 which means seek relative to the current
position and 2 means seek relative to the file's end.
 Example

Assuming that 'foo.txt' file contains following text:


This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readlines()
print ("Read Line: %s" % (line))
fo.seek(0, 0)
line = fo.readline()
print ("Read Line: %s" % (line))
fo.close()

 Output:

Name of the file: foo.txt


Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is
4th line\n', 'This is 5th line']
Read Line: This is 1st line

5.8.5 tell()
 The method tell() returns the current position of the file read/write pointer within the
file.
 Syntax

PPG INSTITUTE OF TECHNOLOGY Page 12


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

fileObject.tell()

 Example

Assuming that 'foo.txt' file contains following text:


This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
pos=fo.tell()
print ("current position : ",pos)
fo.close()

 Output

Name of the file: foo.txt


Read Line: This is 1st line
Current Position: 18

5.8.6 truncate() 
 The method truncate() truncates the file's size.
 If the optional size argument is present, the file is truncated to (at most) that size.
 Syntax

fileObject.truncate( size )

 Example

Assuming that 'foo.txt' file contains following text:


This is 1st line
This is 2nd line
This is 3rd line

PPG INSTITUTE OF TECHNOLOGY Page 13


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

This is 4th line


This is 5th line
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)
line = fo.readline()
print ("Read Line: %s" % (line))
fo.truncate()
line = fo.readlines()
print ("Read Line: %s" % (line))
fo.close()

 Output

Name of the file: foo.txt


Read Line: This is 1s
Read Line: []

5.8.7 next()
 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.
 This method can be used to read the next input line, from the file object
 Syntax

next(iterator,default)

 Example

Assuming that 'foo.txt' contains following lines


C++
Java
Python
Perl
PHP

PPG INSTITUTE OF TECHNOLOGY Page 14


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

fo = open("foo.txt", "r")
print ("Name of the file: ", fo.name)
for index in range(5):
line = next(fo)
print ("Line No %d - %s" % (index, line))
fo.close()

 Output:

Name of the file: foo.txt


Line No 0 - C++
Line No 1 - Java
Line No 2 - Python
Line No 3 - Perl
Line No 4 - PHP

5.8.8 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
 Syntax

fileObject.write(string);

 Example

fo = open("foo.txt", "w")
fo.write( "Python is a great language.\nYeah its great!!\n")
fo.close()

 Output:

Python is a great language.


Yeah its great!!

5.9 FORMATTING OPERATOR


 The string format operator % is unique to strings and used for type conversion.

PPG INSTITUTE OF TECHNOLOGY Page 15


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 When the first operand is a string, % is the format operator.


 The first operand is the format string, which contains one or more format
sequences, which specify how the second operand is formatted.
 The result is a string.
 For example, the format sequence '%d' means that the second operand should be
formatted as an integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels
'42'
 The result is the string '42', which is not to be confused with the integer value 42.
 A format sequence can appear anywhere in the string, so we can embed a value in a
sentence:
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'

S.No. Format Symbol & Conversion

1 %c - character

2 %s - string conversion

3 %i - signed decimal integer

4 %d - signed decimal integer

5 %u - unsigned decimal integer

6 %o - octal integer

7 %x - hexadecimal integer (lowercase letters)

8 %X - hexadecimal integer (UPPERcase letters)

9 %e - exponential notation (with lowercase 'e')

10 %E - exponential notation (with UPPERcase 'E')

5.10 COMMAND LINE ARGUMENTS


 Python provides a getopt module that helps us to parse command-line options and
arguments.
PPG INSTITUTE OF TECHNOLOGY Page 16
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 The Python sys module provides access to any command-line arguments via


the sys.argv.
 This serves two purposes −
 sys.argv is the list of command-line arguments.
 len(sys.argv) is the number of command-line arguments.
 Here sys.argv[0] is the program ie. the script name.
 Example

import sys
print ('Number of arguments:', len(sys.argv), 'arguments.')
print ('Argument List:', str(sys.argv))

 Now run the above script as follows −

$ python test.py arg1 arg2 arg3

 Output

Number of arguments: 4 arguments.


Argument List: ['test.py', 'arg1', 'arg2', 'arg3']

5.10.1 Parsing Command-Line Arguments


 Python provided a getopt module that helps us parse command-line options and
arguments.
 This module provides two functions and an exception to enable command line
argument parsing.
getopt.getopt method
 This method parses the command line options and parameter list. Following is a
simple syntax for this method −

getopt.getopt(args, options, [long_options])

 Here is the detail of the parameters −


 args − This is the argument list to be parsed.
 options − This is the string of option letters that the script wants to recognize,
with options that require an argument should be followed by a colon (:).
 long_options − This is an optional parameter and if specified, must be a list
of strings with the names of the long options, which should be supported.

PPG INSTITUTE OF TECHNOLOGY Page 17


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Long options, which require an argument should be followed by an equal


sign ('=').
 This method returns a value consisting of two elements − the first is a list
of (option, value) pairs, the second is a list of program arguments left after
the option list was stripped.
 Each option-and-value pair returned has the option as its first element,
prefixed with a hyphen for short options (e.g., '-x') or two hyphens for long
options (e.g., '--long-option').
 Example:
import getopt
opts, args = getopt.getopt(['-aval', '-bval', '-cval'], 'a:b:c:')
for opt in opts:
print(opt)
 Output:

('-a', 'val')
('-b', 'val')
('-c', 'val')
5.11 MODULES
 A module allows us to logically organize our Python code.
 Grouping related code into a module makes the code easier to understand and use.
 A module is a Python object with arbitrarily named attributes that we can bind and
reference.
 Simply, a module is a file consisting of Python code.
 A module can define functions, classes and variables.
 A module can also include runnable code.
 Example

def print_func( par ):


print ("Hello : ", par)
return

 The modules can be imported by the following ways:


 The import statement
 The from...import Statement
 The from...import * Statement
PPG INSTITUTE OF TECHNOLOGY Page 18
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

5.11.1 The import Statement
 We can use any Python source file as a module by executing an import statement in
some other Python source file.
 The import has the following syntax:

import module1, module2,...moduleN

 When the interpreter encounters an import statement, it imports the module if the
module is present in the search path.
 For example, to import the module support.py, we need to put the following
command at the top of the script −

import support
support.print_func("Zara")

 Output:

Hello:Zara

 A module is loaded only once, regardless of the number of times it is imported. This
prevents the module execution from happening over and over again if multiple
imports occur.

5.11.2 The from...import Statement
 Python's from statement lets us import specific attributes from a module into the
current namespace.
 The from...import has the following syntax −

from modname import name1, name2,...nameN

 For example, to import the function fibonacci from the module fib, use the following
statement −

from fib import fibonacci

 This statement does not import the entire module fib into the current namespace; it
just introduces the item fibonacci from the module fib into the global symbol table of
the importing module.

PPG INSTITUTE OF TECHNOLOGY Page 19


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

5.11.3 The from...import * Statement:


 It is also possible to import all names from a module into the current namespace by
using the following import statement −

from modname import*

 This provides an easy way to import all the items from a module into the current
namespace; however, this statement should be used sparingly.

5.11.4 The dir( ) Function


 The dir() built-in function returns a sorted list of strings containing the names
defined by a module.
 The list contains the names of all the modules, variables and functions that are
defined in a module.
 Example

# Import built-in module math


import math
content =dir(math)
print (content)

 Output:

['__doc__','__file__','__name__','acos','asin','atan',
'atan2','ceil','cos','cosh','degrees','e','exp',
'fabs','floor','fmod','frexp','hypot','ldexp','log',
'log10','modf','pi','pow','radians','sin','sinh',
'sqrt','tan','tanh']

 Here, the special string variable __name__ is the module's name, and __file__is the
filename from which the module was loaded.

5.12 LOCATING MODULES


 When we import a module, the Python interpreter searches for the module in the
following sequences −
 The current directory.

PPG INSTITUTE OF TECHNOLOGY Page 20


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 If the module is not found, Python then searches each directory in the shell
variable PYTHONPATH.
 If all else fails, Python checks the default path.
 The module search path is stored in the system module sys as the sys.path variable.
The sys.path variable contains the current directory, PYTHONPATH, and the
installation-dependent default.

5.12.1 The PYTHONPATH Variable


 The PYTHONPATH is an environment variable, consisting of a list of directories.
 Example:

set PYTHONPATH = c:\python34\lib;

5.12.2 The globals() and locals() Functions


 The globals() and locals() functions can be used to return the names in the global
and local namespaces depending on the location from where they are called.
 If locals() is called from within a function, it will return all the names that
can be accessed locally from that function.
 If globals() is called from within a function, it will return all the names that
can be accessed globally from that function.
 The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.

5.12.3The reload() Function


 When a module is imported into a script, the code in the top-level portion of a
module is executed only once.
 Therefore, if we want to reexecute the top-level code in a module, we can use
the reload() function.
 The reload() function imports a previously imported module again.
 Syntax:

reload(module_name)

 For example, to reload hello module, do the following −

reload(hello)

PPG INSTITUTE OF TECHNOLOGY Page 21


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

5.13 PACKAGES IN PYTHON


 A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages.

 Steps to create Python Package:

 Create a directory and insert package’s name

 Insert necessary classes into it

 Create a _init_.py fle in that directory

 Example:

#Mobile/MI.py

def MI():

print(“MI Phone”)

#Mobile/G4.py

def G4():

print(“G4 Phone”)

#Create _init_.py in the same (Mobile) directory as follows

from MI import MI

from G4 import G4

#Now import Mobile package

import Mobile

Mobile.MI()

Mobile.G4()

 Output

MI Phone

G4 Phone

PPG INSTITUTE OF TECHNOLOGY Page 22


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

5.14 EXCEPTION HANDLING


 An exception is an event, which occurs during the execution of a program that
disrupts the normal flow of the program's instructions.
 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.
 When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

5.14.1 Handling an exception


 If we have some suspicious code that may raise an exception, we can defend your
program by placing the suspicious code in a try: block.
 After the try: block, include an except: statement, followed by a block of code which
handles the problem as elegantly as possible.
 Syntax

try:
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.

 Here are few important points about the above-mentioned syntax −


 A single try statement can have multiple except statements.
 We can also provide a generic except clause, which handles any exception.
 After the except clause(s), we can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
 The else-block is a good place for code that does not need the try: block's
protection.

PPG INSTITUTE OF TECHNOLOGY Page 23


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Example 1:
This example opens a file, writes content in the, file and comes out gracefully
because there is no problem at all −

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()

 Output:

Written content in the file successfully

 Example 2:
This example tries to open a file where you do not have the write permission, so it
raises an exception −

try:
fh = open("testfile", "r")
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")

 Output:

Error: can't find file or read data

5.14.2 The except Clause with No Exceptions


 We can also use the except statement with no exceptions defined as follows −

try:
You do your operations here
......................

PPG INSTITUTE OF TECHNOLOGY Page 24


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

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.

5.14.3 The except Clause with Multiple Exceptions


 We can also use the same except statement to handle multiple exceptions as follows −

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.

5.14.4 The try-finally Clause


 We can use a finally: block along with a try: block.
 The finally:block is a place to put any code that must execute, whether the try-block
raised an exception or not. The syntax of the try-finally statement is this −

try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

 We can provide except clause(s), or a finally clause, but not both. We cannot
use else clause as well along with a finally clause.
PPG INSTITUTE OF TECHNOLOGY Page 25
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

 Example

try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print ("Error: can\'t find file or read data")
fh.close()

 Output:
If you do not have permission to open the file in writing mode, then this will
produce the following result −

Error: can't find file or read data

5.15 ARGUMENT OF AN EXCEPTION


 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.
 we 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...

 This variable receives the value of the exception mostly containing the cause of the
exception.
 The variable can receive a single value or multiple values in the form of a tuple.
 This tuple usually contains the error string, the error number, and an error location.
 Example

def temp_convert(var):
try:
return int(var)

PPG INSTITUTE OF TECHNOLOGY Page 26


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

except ValueError as Argument:


print ("The argument does not contain numbers\n", Argument)
temp_convert("xyz")

 Output

The argument does not contain numbers


invalid literal for int() with base 10: 'xyz'

5.16 RAISING AN EXCEPTION


 We can raise exceptions in several ways by using the raise statement. The general
syntax for the raise statement is as follows –
 Syntax

raise [Exception [, args [, traceback]]]

 Here, Exception is the type of exception (for example, NameError) and argument is a


value for the exception argument.
 The argument is optional; if not supplied, the exception argument is None.
 The final argument, traceback, is also optional and if present, is the traceback object
used for the exception.
 In order to catch an exception, an "except" clause must refer to the same exception
thrown either as a class object or a simple string.
 Example
a=int(input("Enter a number"))

try:

if a<=0:

raise ValueError("Not a Positive number")

except ValueError as e:

print(e)

else:

print("Positive Number =",a)

 Output:
PPG INSTITUTE OF TECHNOLOGY Page 27
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Enter a number 0

Not a Positive number

5.17 USER-DEFINED EXCEPTIONS


 Python also allows us to create our own exceptions by deriving classes from the
standard built-in exceptions.
 These exceptions are called user-defined exceptions.
 In the try block, the user-defined exception is raised and caught in the except block.
 Example:
class Error(Exception):
pass
class SmallError(Error):
pass
class LargeError(Error):
pass
no=10
while True:
try:
guess=int(input("Guess a number"))
if guess<no:
raise SmallError
elif guess>no:
raise LargeError
else:
break
except SmallError:
print("Valu is too small,try again!")
except LargeError:
print("Valu is too large,try again!")
print("Congratulations! You guessed it correctly")
 Output:
Guess a number 6
Valu is too small,try again!
Guess a number 67
Valu is too large,try again!
PPG INSTITUTE OF TECHNOLOGY Page 28
[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Guess a number 10
Congratulations! You guessed it correctly

5.18 ILLUSTRATIVE PROGRAMS:


Program to count words in file
import collections
myfile = open("input.txt", "r")
file = myfile.read()
print(file)
words = file.split()
most_frequent = collections.Counter(words)
print(most_frequent)

Output

Input File: input.txt

Python is Simple
Python is interactive programming language
Python is Interpreted

Output:
Python is Simple
Python is interactive programming language
Python is Interpreted
Counter({'Python': 3, 'is': 3, 'Simple': 1, 'interactive': 1, 'programming': 1, 'language':
1, 'Interpreted': 1})

PPG INSTITUTE OF TECHNOLOGY Page 29


[GE8151 PROBLEM SOLVING & PYTHON PROGRAMMING] [Pick the date]

Program to copy the content of one file to another


with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
Output:

Case 1:
Contents of file(test.txt):
Hello world
 
Output(out.text):
Hello world

PPG INSTITUTE OF TECHNOLOGY Page 30

You might also like