MCA Python-unit3-File& Exception Handling Notes
MCA Python-unit3-File& Exception Handling Notes
UNIT III
Files:
File is a named location on disk to store the related information. A collection of data or
information that has a name is called the file name. All information stored in a computer must be
in a file.
Types of files:
i) Data files
ii) Text files
iii) Program files
iv) Directory
files
Text files
Text file is a sequence of characters stored on a permanent medium like hard drive, flash
memory (or) CD-ROM. In addition to printable characters, the text file contains non printing
characters. So a text file contain letters (a-z/A-Z), numbers (0-9), special symbols ($,#),non
printing characters(\n,\t,\b) etc. Text file should be saved with the extension .txt.
File operations
In Python, a file operation takes place in the following order.
i) Opening the file
ii) Reading and writing (perform operation)
iii) Closing the file
i) Opening the file
When the user wants to read or write to a file, user needs to open it first. Python has a
built-in function open () to open a file.
Syntax:
fileobject=open(“filename”, ”access mode”)
The parameters are explained below:
filename The filename argument is a string value that contains the name of the file to access.
access mode The access mode denotes the mode in which the file has to be opened (read, write,
append, etc).
Example:
>>>f=open(“test.txt”,”w”)
File opening modes:
There are various modes while opening a file. They are,
Modes Description
Opens a file for reading only. The file pointer is placed at the beginning of
r
the file.
Opens a file for reading only in binary format. The file pointer is placed at
rb
the beginning of the file. This is the default mode.
Opens a file for both reading and writing. The file pointer placed at the
r+
beginning of the file.
Opens a file for both reading and writing in binary format. The file pointer
rb+
placed at the beginning of the file.
Opens a file for writing only. Overwrites the file if the file exists. If the
w
file does not exist, creates a new file for writing.
Opens a file for writing only in binary format. Overwrites the file if the
wb
file exists. If the file does not exist, creates a new file for writing.
Opens a file for both writing and reading. Overwrites the existing file if
w+ the file exists. If the file does not exist, creates a new file for reading
and
writing.
Opens a file for both writing and reading in binary format. Overwrites the
wb+ existing file if the file exists. If the file does not exist, creates a new file
for reading and writing.
Opens a file for appending. The file pointer is at the end of the file if the
a file exists. If the file does not exist, it creates a new file for writing.
Opens a file for appending in binary format. The file pointer is at the end
ab
of the file if the file exists. If the file does not exist, it creates a new file
for writing.
Opens a file for both appending and reading. The file pointer is at the end
a+ of the file if the file exists. If the file does not exist, it creates a new file
for reading and writing.
Opens a file for both appending and reading in binary format. The file
ab+ pointer is at the end of the file if the file exists. If the file does not exist, it
creates a new file for reading and writing.
Attribute Description
Returns true if the file is closed,
file.closed
otherwise false.
Returns the file access mode with which
file.mode
file was opened.
file.name Returns name of the file.
ii) Reading and writing files
Python provides read () and write () methods to read and write files through file object
respectively.
Reading files:
The read() method read the file contents, from opened file. To read the content of file, the
file must be opened in read mode (r).There are 4 methods for reading files.
i ) Reading a file using read(size) method
ii) Reading a file using for loop
iii) Reading a file using readline() method
iv) Reading a file using readlines() method
The file test.txt contains
Problem solving and python
programming. Introduction to python
The read(size) method is used to read in size number of data.If the size parameter is notspecified, it
reads and returns up to the end of file.
Syntax:
fileobject . read([size])
Example:
f=open(“test.txt”, “r+”)
S=f.read(15);
print(“Read string is:”,S)
f.close()
Output:
Read string is: problem solving
i) Reading a file using for loop
A file can be read using for loop. This method is efficient and fast.
Syntax:
for loopvariable in
fileobject:
print(loopvariable)
Example Program:
f=open(“test.txt”, “r+”)
for i in f:
print(i)
f.close()
Output:
Problem solving and python programming
Introduction to python
ii) Reading a file using readline() method
The readline() method is used to read individual line of a file. It reads a file till the
newline(\n) character is reached (or) end of file is reached.
Syntax:
fileobject . readline()
Example Program:
f=open(“test.txt”, “r+”)
f.readline()
f.close()
Output:
Problem solving and python programming
iii) Reading a file using readlines() method
The readlines() method is used to read all the lines of file at a time.
Syntax:
fileobject.readlines()
Example Program:
f=open(“test.txt”, “r+”)
f.readlines()
f.close()
Output:
Problem solving and python programming
Introduction to python
Writing files:
The write() method is used to write the contents into the file. To write the file contents,
the file must be opened into following mode.
w-writing mode
a-appending mode
x-exclusive creation
The „w‟ mode will overwrite into the file if already exists. So all previous data‟s are erased.
Syntax:
fileobject . write(string)
Example Program:
f=open(“test.txt”, “r+”)
f.write(“Welcome to
python”) f.close()
Example Program:
>>>x=15
>>>”%d”%x
15
%d is formatted as decimal integer.
Format sequence in string:
Format sequence can appear anywhere in the string
Example Program:
>>>computers=10
>>>‟I have bought %d computers‟, %computers
Output:
I have bought 10 computers
More than one format sequence:
If there is more than one format sequence, second argument must be tuple.
Example Program:
>>>”In %d years, I have bought %g%s”.%(2,3.0,‟computers‟)
In 2 years, I have bought 3.0 computers
In the above program:
%d is formatted to integer
%g is formatted to floating point number
%s is formatted to string.
Number of elements in tuple and number of format sequences must be same.
COMMAND LINE ARGUMENTS
Command line arguments are what we type at the command line prompt along with the
script name while we try to execute our script other languages.
Command line argument in python can be processed by using two modules.
i) sys module
ii) argparse module
i) sys module
Sys module is used to access the command line arguments through sys.argv. The sys
module is used for two purposes.
i) sys.argv is a list in Python, which contains the command line arguments passed to the script.
Errors
print (10/0)
ZeroDivisionError: integer division or modulo by zero
Exceptions come in different types, and the type is printed as part of the message: the
type in the example is ZeroDivisionError which occurs due to division by 0. The string printed as
the exception type is the name of the built-in exception that occurred. Exception refers to
unexpected condition in a program. The unusual conditions could be faults, causing an error
which in turn causes the program to fail. The error handling mechanism is referred to as
exception handling. Many programming languages like C++, PHP, Java, Python, and many
others have built-in support for exception handling.
Python has many built-in exceptions which forces your program to output an error
when something in it goes wrong. When these exceptions occur, it stops the current process and
passes the control to corresponding exception handler. If not handled, our program will crash.
Some of the standard exceptions available in Python are listed below.
Exception Name Description
Exception Base class for all exceptions
ArithmeticError Base class for all errors that occur for numeric
calculation.
OverflowError Raised when a calculation exceeds maximum limit for
a numeric type.
FloatingPointError Raised when a floating point calculation fails.
ZeroDivisionError Raised when division or modulo by zero takes place
for all numeric types.
AssertionError Raised in case of failure of the Assert statement
EOFError Raised when there is no input from either the
raw_input() or input() function and the end of file is
reached.
ImportError Raised when an import statement fails.
IndexError Raised when an index is not found in a sequence
KeyError Raised when the specified key is not found in the
dictionary.
HANDLING EXCEPTIONS
The simplest way to handle exceptions is with a “try-except” block. Exceptions that
are caught in try blocks are handled in except blocks. If an error is encountered, a try block code
execution is stopped and control transferred down to except block.
Syntax:
try:
statements
Except exception1:
Except exception2:
follows.
i) First, the try block (the statement(s) between the try and except keywords)
is executed.
ii) If no exception occurs, the except block is skipped and execution of the try statement
is finished.
iii) If an exception1 occurs rest of try block is skipped, except block1 gets executed.
iv) If an exception2 occurs rest of try block is skipped, except block2 gets
executed.
A simple example to handle divide by zero error is as follows.
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError:
print “divide by zero”
Output:
divide by zero
A try statement may have more than one except clause, to specify handlers for different
exceptions. If an exception occurs, Python will check each except clause from the top down to
see if the exception type matches. If none of the except clauses match, the exception will be
Syntax:
try:
# statements
break
except ErrorName1:
# handler
code except
ErrorName2:
# handler code
A simple example to handle multiple exceptions is as follows.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except ValueError:
print(“The divisor and dividend have to be numbers!”)
except ZeroDivisionError:
print(“The dividend may not be zero!”)
Output (successful):
Please enter the dividend: 12
Please enter the divisor: 2
12 / 2 = 6.000000
Output (unsuccessful-divide by zero error):
Please enter the dividend: 100
Please enter the divisor: 0
The dividend may not be zero!
An except clause may name multiple exceptions as a parenthesized tuple, for example:
Example:
try:
raise NameError
except NameError:
print(„Error‟)
Output:
Error
raise without any arguments is a special use of python syntax. It means get the exception
and re-raise it. The process is called as re-raise. If no expressions are present, raise re-raises the
last exception that was active in the current scope.
Example:
try:
raise NameError
except NameError:
print(„Error‟)
raise
Output:
Error
Traceback (most recent call last):
File “main.py”, line 2, in <module>
raise NameError(„Hi‟)
NameError: Hi
In the example, raise statement inside except clause allows you to re-raise the exception
NameError.
The else and finally statements
Two clauses that can be added optionally to try-except block are else and finally. else
will be executed only if the try clause doesn‟t raise an exception.
try:
age = int(input(“Please enter your age:
“)) except ValueError:
Output:
Please enter your age:10
I see that you
are 10 years
old. Please
enter your
age:‟a‟
Value error occured
User-defined exceptions
Python allows the user to create their custom exceptions by creating a new class.
This exception class has to be derived, either directly or indirectly, from Exception class.
# define Python user-
defined exceptions class
Error(Exception):
“””Base class for other
exceptions””” pass #
null operation
class PosError(Error):
“””Raised when the input
value is positive””” pass
class NegError(Error):
“””Raised when the input value
is negative””” Pass