Problem Solving Python Programming Unit - V
Problem Solving Python Programming Unit - V
Files and exceptions: text files, reading and writing files, format operator; command line arguments, errors
and exceptions, handling exceptions, modules, packages; Illustrative programs: word count, copy file, Voter’s age
validation, Marks range validation (0-100).
Opening a file:
This function creates a file object, which would be utilized to call other support methods associates with it.
Modes Description
Open a file for reading only. The file pointer is placed at the beginning of the
r
file. This is default mode.
Open a file for reading only in binary format. The file pointer is placed at the
rb
beginning of the file. This is default mode.
Open a file for both read and write. The file pointer is placed at the beginning of
r+
the file.
Open a file for both read and write in binary format. The file pointer is placed at
rb+
the beginning of the file
Open a file for writing only. Overwrite the file if exists. If the files does not
w
exists, creates a new file for writing.
1
Open a file for writing only in binary format. Overwrite the file if exists. If the
wb
files does not exists, creates a new file for writing.
Open a file for both read and write. Overwrite the file if exists. If the files does
w+
not exists, creates a new file for writing and reading.
Open a file for both read and write in binary format. Overwrite the file if exists.
wb+
If the files does not exists, creates a new file for writing and reading.
a Open a file for appending. This file pointer is placed at the end of the file.
Open a file for appending only in binary format. This file pointer is placed at the
ab end of the file, if exists. That is, the file is in the appending mode. If the files
does not exists, creates a new file for writing.
Open a file for appending and reading. This file pointer is placed at the end of
a+
the file, if exists.
Open a file for appending and reading in binary format. This file pointer is placed
ab+
at the end of the file, if exists. It creates a new file for reading and writing.
Example: fn=open(‘D:/[Link]’,’r’)
Syntax : [Link](“filename”,”mode”)
Example:
f=open(‘D:/[Link]’,’w’)
[Link](“welcome\n”)
[Link](“thank you”)
[Link]()
Syntax:
with open (filename, mode) as variable :
block
Example:
with open (“[Link]”, “r”) as file:
contents=[Link]( )
Print(contents)
2
Writelines():
The writelines method put multiple data into the file.
The writelines() method writes any string to an open file.
Syntax: [Link](string)
[Link]:
Output:
f=open(‘D:/[Link]’,’w’)
This is my book
str=‘this is my book\n I found it here’ I found it here
[Link](str)
[Link]()
Reading a file:
This method helps to just view the content of given input files. To read the content of a file, one must open the
file in reading mode.
Syntax: filevariable=open(‘filename’,’r’)
Methods used in reading a file.
1. read(size)
2. Readline()
3. Readlines()
[Link](size)
This read() specifies the size of data to be read from input files.
If size not mentioned, it reads the entire files and cursor waits in last position of files.
Ex.
f=open(“[Link]”, ”r”)
print(“The first 5 characters of the file are:\n”, [Link](5))
[Link]()
OUTPUT:
3
Readline():
This method is used to read a single line from the input file, till the new line character occur.
It doesn’t takes any argument.
Syntax: [Link]()
ex.
f=open(“[Link]”,”r”)
print(“reading content of the file by realine() method:\n”)
print([Link]())
[Link]()
Readlines():
This method is used to read and display all the line from the input file.
Syntax: [Link]()
ex.
f=open(“[Link]”,”r”)
print(“reading content of the file by realines() method:\n”)
print([Link]())
[Link]()
encoding: It returns the encoding this file uses, such as UTF-8. This attribute is read-only. When Unicode
strings are written to a file, they will be converted to byte strings using this encoding. It may also be None. In that
case, the file uses the system default encoding for converting Unicode strings.
mode: Returns the file access mode used while opening a file.
closed: Returns True if a file is closed. It is a Boolean value indicating the current state of the file object.
newline: Files opened in universal newline read mode keep track of the newlines encountered while reading
the file. The values are ‘\r’, ‘\n’, ‘\r\n’, None (no newlines read yet), or a tuple containing all the newline types seen.
For files not opened in universal newline read mode, the value of this attribute will be None.
Closing a file:
The close() methods of a file object flushes any unwritten information and closes the file object, after which
no more writing can be done.
Syntax: [Link]()
[Link]: Output:
Open(‘[Link]’,’wb’) Name of the file: [Link]
4
Example: Python program to implement all file read operation:
fn=open(‘D:/[Link]’,’r’)
print([Link]())
[Link](0)
Output:
print([Link](4)) Welcome to the world of robotics
print([Link]()) Welc
4
[Link](0) Welcome to the world of robotics
Welcome to the world of robotics
print([Link]()) and automation
[Link](0)
print([Link]())
[Link]:
Welcome to the world of robotics
and automation
FILE METHODS
Methods Description
[Link]() Close the file. A closed file cannot be read or write anymore.
Flush the internal buffer, like stdio’s fflush. This may be a no-op on
[Link]()
some file like objects.
Return the integer file description that is used by underlying
[Link]()
implementation to request I/O operation from os.
[Link]() Return True if the file is connected to a tty(-like) devices, else False.
Read at most size bytes from files (less if the read hits EOF before
[Link]([size])
obtaining size bytes)
Read one entries line from the file. A trailing newline character is kept
[Link]([size])
in the string.
Read until EOF using readline() and return a list containing the lines.
[Link]([sizehint]) If the optional sizehint of argument is present, instead of reading up to
EOF, whole line totaling approximately sizehint bytes are read.
[Link](offset[,whence]) Set the files current position.
[Link]() Return the files current position
Truncates the files size. If the optional size argument is present, the file
[Link]([size])
is truncated to that size.
[Link](str) Writes a string to the files. There is no return value.
Writes a sequence of string to a file. The sequences can be any
[Link](sequence)
iterable. Object producing string, typically a list of strings.
[Link]() Return true if file stream can be read from.
[Link]() Return true if file stream supports random access.
[Link](0 Return true if file stream can be written to.
5
Tell() and seek():
Tell() method display the current position of cursor from the input files.
Seek() takes an argument and moves the cursor to the specified position which is mentioned as argument.
Syntax: print([Link]())
print([Link]())
Example:
fn=open(‘D:/[Link]’,’r’)
print([Link]())
[Link](0)
print([Link](4)) Output:
print([Link]()) Welcome to the world of robotics
[Link](0) Welc
print([Link]()) 4
[Link](0) Welcome to the world of robotics
print([Link]()) Welcome to the world of robotics
and automation
[Link]:
Welcome to the world of robotics
and automation
FORMAT OPERATOR
String formatting is the process of infusing things in the strings dynamically and presenting the strings.
There are four different ways to perform string formatting.
1. Formatting with % operator
2. Formatting with format() string methods.
3. Formatting with string literals, called f-strings.
4. String template class
6
Example:
print('We all are {}.'.format('equal'))
Output: We all are equal.
The format() method has many advantages over the placeholder method:
We can insert object by using index-based position:
Example: print('{2} {1} {0}'.format('directions','the', 'Read'))
Output: Read the directions.
Syntax: {[index]:[width][.precision][type]}
Output:
The value of pi is: 3.14159
The value of pi is: 3.14159
7
COMMAND LINE ARGUMENT
The arguments that are given after the name of the program in the command line shell of the operating
system are known as Command Line Arguments. Python provides various ways of dealing with these types of
arguments. The three most common are:
1. Using [Link]
2. Using argparse module
[Link] [Link]:
The sys module provides functions and variables used to manipulate different parts of the Python runtime
environment. This module provides access to some variables used or maintained by the interpreter and to functions
that interact strongly with the interpreter.
One such variable is [Link] which is a simple list structure. It’s main purpose are:
It is a list of command line arguments.
len ([Link]) provides the number of command line arguments.
[Link][0] is the name of the current Python script.
Example: Let’s suppose there is a Python script for adding two numbers and the numbers are passed as command-
line arguments.
# total arguments
n = len ([Link])
print ("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", [Link][0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print([Link][i], end = " ")
Output:
8
2. Using argparse module:
Using argparse module is a better option than the above two options as it provides a lot of options such as
positional arguments, default value for arguments, help message, specifying data type of argument etc.
Example:
import argparse
# Initialize parser
parser = [Link]()
parser.parse_args()
Output:
9
The run time errors are not detected while parsing the source program, but will occur due to some logical
mistake.
Eg of runtime error are:
1) Trying to access a file which does not exist.
2) Using an identifier which is not defined.
3) Performing operations of incompatible type elements
4) Division by Zero
Such errors are handled using exception handling.
2 StopIteration If the next() method returns null for an iterator, this exception is raised.
Excluding the StopIteration and SystemExit, this is the base class for all
4 StandardError
Python built-in exceptions.
This exception is raised when a computation surpasses the numeric data type's
6 OverflowError
maximum limit.
For all numeric data types, its value is raised whenever a number is attempted
8 ZeroDivisionError
to be divided by zero.
When the endpoint of the file is approached, and the interpreter didn't get any
11 EOFError
input value by raw_input() or input() functions, this exception is raised.
12 ImportError This exception is raised if using the import keyword to import a module fails.
15 IndexError This exception is raised when the index attempted to be accessed is not found.
When the given key is not found in the dictionary to be found in, this exception
16 KeyError
is raised.
This exception is raised when a variable isn't located in either local or global
17 NameError
namespace.
10
This exception is raised when we try to access a local variable inside a
18 UnboundLocalError
function, and the variable has not been assigned any value.
19 EnvironmentError All exceptions that arise beyond the Python environment have this base class.
If an input or output action fails, like when using the print command or the
20 IOError
open() function to access a file that does not exist, this exception is raised.
22 SyntaxError This exception is raised whenever a syntax error occurs in our program.
This exception is raised when the [Link]() method is used to terminate the
24 SystemExit Python interpreter. The parser exits if the situation is not addressed within the
code.
This exception is raised if the parameters for a built-in method for a particular
26 ValueError
data type are of the correct type but have been given the wrong values.
This exception is raised when an error that occurred during the program's
27 RuntimeError
execution cannot be classified.
If an abstract function that the user must define in an inherited class is not
28 NotImplementedError
defined, this exception is raised.
Handling an exception
When it raises an exception, it must either handle the exception immediately else it terminates and
quits. The exception handling mechanism uses the try….except…..else blocks.
try: includes suspicious code.
After the try: block, include an except: statement, followed by a block of code which handles the problem as
elegantly as possible.
Syntax
Here is simple syntax of try....except...else blocks −
try:
write the suspicious code 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.
Note:
1. A single try statement can have multiple except statements. This is useful when the try block contains
statements that may throw different types of exceptions.
2. You can also provide a general except clause, which handles any exception.
3. After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in
the try: block does not raise an exception.
4. The else-block is a good place for code that does not need the try: block's protection.
11
Example 1:
try:
fh = open("testfile", "w")
[Link]("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"
[Link]()
Output:
Written content in the file successfully
Example 2:
try:
fh = open("testfile", "r")
[Link]("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
Example:
try:
n=int(input(“Enter some number”))
except
print(“you have entered wrong data”)
else:
print(“You have entered:”,n)
Output:
Enter some number a
You have entered a wrong data
Enter some number 10
You have entered :10
Note: This kind of a try-except statement catches all the exceptions that occur.
12
The except Clause with Multiple Exceptions:
You can also use the same except statement to handle multiple exceptions as follows −
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.
Example:
try:
a=int(input(“Enter the value of a”))
b=int(input(“Enter the value of b”))
c=a/b
except value error:
print (“You have entered wrong data”)
except Zerodivision error:
print (“Divide by zero error!!!”)
else:
print (“The result”,c)
Output:
Enter the value of a:10
Enter the value of b:a
You have entered wrong data
Syntax:
try:
You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................
Example:
try:
fh = open("testfile", "w")
[Link]("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
Output:
Error: can't find file or read data
13
Raising an Exceptions:
You 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 rarely used in practice), and if present, is the traceback
object used for the exception.
Example:
User-Defined Exceptions:
Python also allows you to create your own exceptions by deriving classes from the standard built-in exceptions.
Here is an example related to RuntimeError. Here, a class is created that is subclassed from RuntimeError.
This is useful when you need to display more specific information when an exception is caught.
In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to
create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
[Link] = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print [Link]
14
MODULES
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module makes the
code easier to understand and use.
Example:
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Example:
# importing module [Link]
import calc
print([Link](10, 2))
Output: 12
Output:
4.0
720
Import all Names :
The * symbol used with the from import statement is used to import all the names from a module to a current
namespace.
Syntax:
from module_name import *
Example:
from math import *
print(sqrt(16))
print(factorial(6))
Output: 4.0
720
15
# module math
import math as mt
print([Link](16))
print([Link](6))
Example:
import math
print([Link](25))
print([Link])
print([Link](2))
print([Link](60))
print([Link](2))
print([Link](0.5))
print([Link](0.23))
print([Link](4))
import random
print([Link](0, 5)) # printing random integer between 0 and 5
print([Link]()) # print random floating point number between 0 and 1
print([Link]() * 100) # random number between 0 and 100
List = [1, 4, True, 800, "python", 27, "hello"]
print([Link](List))
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print([Link]())
# Converts a number of seconds to a date object
print([Link](454554))
16
Packages
A package is a collection of modules. A Python package can have sub-packages and modules. A directory
must contain a file named __init__.py in order for Python to consider it as a package. This file can be left empty but
we generally place the initialization code for that package in this file.
17
ILLUSTRATIVE PROGRAM
1. Word Count [Link] files:
import sys def copyFile(oldFile, newFile):
file=open("/Python27/[Link]","r+") f1 = open(oldFile, "r")
wordcount={} f2 = open(newFile, "w")
for word in [Link]().split(): while True:
if word not in wordcount: text = [Link](50)
wordcount[word] = 1 if text == "":
else: break
wordcount[word] += 1 [Link](text)
[Link](); [Link]()
print ("%-30s %s " %('Words in the File' , 'Count')) [Link]()
for key in [Link](): return
print ("%-30s %d " %(key , wordcount[key]))
[Link] is an exception?
Whenever a runtime error occurs, it creates an exception. The program stops execution and prints an error
message.
Example:
#Dividing by zero creates an exception: print 55/0
ZeroDivisionError: integer division or modulo
18
[Link] are the two parts in an error message?
The error message has two parts: the type of error before the colon, and specification about the error after
the colon.
Example:
>>> 10 * (1/0)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
[Link] are the error messages that are displayed for the following exceptions?
1. Accessing a non-existent list item
2. Accessing a key that isn’t in the dictionary
3. Trying to open a non-existent file
4. IndexError: list index out of range
5. KeyError: what
6. IOError: [Errno 2] No such file or directory: 'filename'
[Link] do you handle the exception inside a program when you try to open a non-existent file?
filename = raw_input('Enter a file name: ') try:
f = open (filename, "r") except IOError:
print 'There is no file named', filename
[Link] is the function of raise statement? What are its two arguments?
The raise statement is used to raise an exception when the program detects an error. It takes two
arguments: the exception type and specific information about the error.
[Link] is a pickle?
Pickling saves an object to a file for later retrieval. The pickle module helps to translate almost any type of
object to a string suitable for storage in a database and then translate the strings back in to objects.
To store a data structure, dump method is used and to load the data structures that are dumped, load
method is used.
19
[Link] is a package?
Packages are namespaces that contain multiple packages and modules themselves. They are simply
directories.
Example:
from [Link]
import select_difficulty
[Link] a Python script to display the current date and time. (Jan-2018)
import datetime
print(“date and time”, [Link]())
[Link] is the special file that each package in Python must contain?
Each package in Python must contain a special file called init .py. init .py can be an empty file but it
is often used to perform setup needed for the package(import things, load things into path, etc).
Example :
package/
init .py [Link] [Link] [Link] subpackage/
init .py [Link] [Link]
[Link] do you use command line arguments to give input to the program? (or) What is command line
argument? (May 2019) (Nov / Dec 2019)
Python sys module provides access to any command-line arguments via [Link]. [Link] is the list of
command-line arguments. len([Link]) is the number of command-line arguments.
Example:
import sys
program_name = [Link][0]
arguments = [Link][1:]
count = len(arguments)
20
[Link] the syntax error in the code given:
while True print(‘Hello World’) (Jan 2019)
In the above given program, colon is missing after the condition. The right way to write the above program is,
while True:
print(‘Hello World’)
[Link] the different types errors arises during programming. Interpret the following python code
>>>import os (May 2019)
>>>cwd = [Link]()
>>>print cwd
21