Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
86 views

mc4103 Python Programing

python

Uploaded by

sivaranjanimln
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

mc4103 Python Programing

python

Uploaded by

sivaranjanimln
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

lOMoARcPSD|38080204

MC4103 - Python Programing

Python programming (Anna University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)
lOMoARcPSD|38080204

UNIT III

FILE HANDLING ND EXCEPTION HANDLING

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,

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

append, etc).

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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.

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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.

The file object attributes:

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

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

i) Reading a file using read(size) method

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

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

iii) Closing the file


The function close() of a file object flushes if there is any unwritten information and
closes the file object when there is no more writing can be done. Python closes a file
automatically when the reference object of a file is reassigned with another file. The syntax of
close () function is given below.
Syntax:
fileobject.close()
Example Program:
f1=open(“test.txt”,”w”)
print(“Name of file is:”,f1.name)
print(“closed or not:”,f1.closed)
print(“opening mode is:”,f1.mode)
f1.close()
Output:
Name of file
is:test.txt closed or
not:False opening
mode is:w
Format Operator
write() function takes the argument as a string . To put other values in a file, it must be
converted to strings. It is done by 2 methods:
i) str() method is used to convert other values into string.
Example Program:
>>>x=52
>>>f.write(str(x))
52
ii) Format operator is an % operator that converts other values into
string. with integers, % is considered as modulus operator
with strings,% is considered as format operator

Example Program:
>>>x=15

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

>>>”%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.

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

ii) len(sys.argv) is used to count the number of arguments


There are three steps followed in sys module
i) Import the sys module
ii) We can use sys.argv for getting the list of command line arguments.
iii) Use len(sys.argv) for getting length of command line arguments.
Example Program:
import sys
print „No. of arguments:‟, len(sys.argv)
print „Argument List:‟,str(sys.argv)
Run the above script as follows:
$ python test.py arg1 arg2 arg3
Output:
Number of arguments: 4
Argument List: [„test.py‟, „arg1‟,‟arg2‟,‟arg3‟]
ii) argparse module
argparse module is used to access command line arguments. It includes tools for building
command line arguments. There are three steps followed in arg parse module.
i) Import argparse module
ii) Use ArgumentParser for parsing command line arguments
iii) Use parseargs() method to parse command line arguments.
Example Program:
Import argparse
Parser=argparse.ArgumentParser()
Parser.parseargs()
Output:
>>>python cmdline.py –h
Usage:cmdline.py[- h]
Optional arguments
-h,--help show message

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

ERRORS AND EXCEPTIONS


Errors
Errors or mirrors in a program are often referred to as bugs. Error is mistakes in the
program, which are created by fault of the programmer.
Debugging:
Debugging is the process of finding and eliminating errors.

Errors

Syntax error Runtime error Logical error

Missing of colon Division by zero Access not Using operator precedence


Mis spelling Using wrong
keyword ,comma defined
wrong variable

Fig: 5.1: Types of errors


Types of errors:
i) Syntax errors
ii) Runtime errors
iii) Logical error
i) Syntax errors
Syntax error occurs when the program is not following the proper structure (syntax).
If syntax errors occur then python display error message and exit without continuing execution
process.

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

Some of syntax errors are:


Misspelling keyword
Incorrect indentation
Missing of colon, comma
Leaving a keyword
Putting a keyboard in wrong place
Here are some examples of syntax errors in Python:
a=5
b=20
if a<b
print „a is
greater‟ Error Message:
File “main.py”, line 3
if a<b
^
ii) Runtime errors
Runtime errors occur during execution of program. It is also known as dynamic errors.
Some of runtime errors are:
Division by Zero
Access not defined identifier
Access not defined file
Example:
>>>b= [1,2,3,4]
>>>a
Runtime Error:‟a‟ is not defined
>>>a=5
>>>b=10
>>>a/b
Runtime Error:‟Division by Zero‟

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

iii) Logical errors


Logical error occurs due to mistake in program‟s logic. Here program runs without any
error messages, but produces an incorrect result. These errors are difficult to fix. Here are some
logical errors are:
 Using the wrong variable name
 Indenting a block to the wrong level
Using integer division instead of floating-point division
Using wrong operator precedence
 Making a mistake in a Boolean expression
Off-by-one and other numerical errors
Example:Addition of two numbers
>>>x=10
>>>y=20
>>>z=x-y #Logic error
>>>print z
-10
Here, parentheses are missing. So we get wrong result.
Exceptions
An exception is an error that occurs during execution of a program. It is also called as run
time error. Some examples of Python runtime errors:
division by zero
performing an operation on incompatible types
using an identifier which has not been defined
accessing a list element, dictionary value or object attribute which doesn‟t exist
trying to access a file which doesn‟t
exist An example for run time error is as follows:
print (10/0)
Error Message:
Traceback (most recent call last):
File “main.py”, line 1, in <module>

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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.

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

NameError Raised when an identifier is not found in the local or


global namespace
IOError Raised when an input/ output operation fails, such as
the print statement or the open() function when trying
to open a file that does not exist.
SyntaxError Raised when there is an error in Python syntax
SystemExit Raised when Python interpreter is quit by using the
sys.exit() function. If not handled in the code, causes
the interpreter to exit
TypeError Raised when an operation or function is attempted
that is invalid for the specified data type
ValueError Raised when the built-in function for a data type has
the valid type of arguments, but the arguments have
invalid values specified.
RuntimeError Raised when a generated error does not fall into any
category

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.

Try Raise Except

Exception Raise theHandling


Fig 5.2: Exception Catch if
exception
may occur Exception

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

Syntax:
try:
statements

Except exception1:

If exception1 occurs execute it.

Except exception2:

If exception2 occurs execute it.

The try statement works as

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

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

considered unhandled, and your program will crash.

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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!

Output (unsuccessful-value error):


Please enter the dividend: „e‟
The divisor and dividend have to be numbers!

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

An except clause may name multiple exceptions as a parenthesized tuple, for example:

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

... except (RuntimeError, TypeError, NameError):


...#handlercode
Example:
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, ZeroDivisionError):
print(“Oops, something went wrong!”)
Output:
Please enter the dividend:
110 Please enter the divisor: 0
Oops, something went wrong!
To catch all types of exceptions using single except clause, simply mention except
keyword without specifying error name. It is shown in following example.
try:
dividend = int(input(“Please enter the dividend: “))
divisor = int(input(“Please enter the divisor: “))
print(“%d / %d = %f” % (dividend, divisor, dividend/divisor))
except
:
print(“Oops, something went wrong!”)
Raising exceptions
The raise statement initiates a new exception. It allows the programmer to force a
specified exception to occur. The raise statement does two things: it creates an exception object,
and immediately leaves the expected program execution sequence to search the enclosing try
statements for a matching except clause. It is commonly used for raising user defined exceptions.
Syntax of two forms of the raise statement are:
raise ExceptionClass(value)
raise Exception

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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:

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

print(“Value error occured”)


else
:
print(“I see that you are %d years old.” % age)

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)


lOMoARcPSD|38080204

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

Downloaded by sivaranjani sivaranjani (sivaranjanimln@gmail.com)

You might also like