GE4105 - PSPP - Unit V - Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

UNIT V

FILES, MODULES, PACKAGES


5.1 FILES
Most of the programs we have seen so far are transient in the sense that they
run for a short time and produce some output, but when they end, their data disappears. If you
run the program again, it starts with a clean slate.

Other programs are persistent: they run for a long time (or all the time); they keep at least
some of their data in permanent storage (a hard drive, for example); and if they shut down
and restart, they pick up where they left off.

One of the simplest ways for programs to maintain their data is by reading and
writing text files. An alternative is to store the state of the program in a database.

5.1.1 Text Files

A text file is a sequence of characters stored on a permanent medium like a hard


drive, flash memory, or CD-ROM. Text file contain only text, and has no specialformatting
such as bold text, italic text, images, etc. Text files are identified with the .txt file extension.

5.1.2 Reading and Writing to Text Files

Python provides inbuilt functions for creating, writing and reading files. There
are two types of files that can be handled in python, normal text files and binary files (written
in binary language,0s and 1s).
➢ Text files: In this type of file, each line of text is terminated with a special character
called EOL (End of Line), which is the new line character (‗\n‘) in python by default.
➢ Binary files: In this type of file, there is no terminator for a line and the data is stored
after converting it into machine understandable binary language.
In order to perform some operations on files we have to follow below steps
➢ Opening
➢ Reading or writing
➢ Closing
Here we are going to discusses about opening, closing, reading and writing data in a text file.

5.1.2.1 File Access Modes


Access modes govern the type of operations possible in the opened file. It refers
to how the file will be used once its opened. These modes also define the location of the File
Handle in the file. File handle is like a cursor, which defines from where the data hasto be read
or written in the file. There are 6 access modes in python.

➢ Read Only (‘r’) : Open text file for reading. The handle is positioned at the beginning
of the file. If the file does not exists, raises I/O error. This is also the default mode in
which file is opened.
➢ Read and Write (‘r+’) : Open the file for reading and writing. The handle is positioned
at the beginning of the file. Raises I/O error if the file does not exists.
➢ Write Only (‘w’) : Open the file for writing. For existing file, the data is truncated and
over-written. The handle is positioned at the beginning of the file. Creates the file if the
file does not exists.
➢ Write and Read (‘w+’) : Open the file for reading and writing. For existing file, data
is truncated and over-written. The handle is positioned at the beginning of the file.
➢ Append Only (‘a’) : Open the file for writing. The file is created if it does not exist.
The handle is positioned at the end of the file. The data being written will be inserted
at the end, after the existing data.
➢ Append and Read (‘a+’) : Open the file for reading and writing. The file is created if
it does not exist. The handle is positioned at the end of the file. The data being written
will be inserted at the end, after the existing data.

5.1.3 Opening a File


It is done using the open() function. No module is required to be imported for
this function.
Syntax:
File_object = open(r"File_Name","Access_Mode")
The file should exist in the same directory as the python program file else, full
address (path will be discussed in later section of this unit) of the file should be written on place
of filename. Note: The r is placed before filename to prevent the characters in filename string
to be treated as special character. For example, if there is \temp in the file address, then
\t is treated as the tab character and error is raised of invalid address. The r makes the string
raw, that is, it tells that the string is without any special characters. The r can be ignored if the
file is in same directory and address is not being placed.
Example:

>>> f1 = open("sample.txt","a")
>>> f2 = open(r"G:\class\python\sample3.txt","w+")

Here, f1 is created as object for sample.txt and f3 as object for sample3.txt


(available in G:\class\python directory)

5.1.4 Closing a File


close() function closes the file and frees the memory space acquired by that file.
It is used at the time when the file is no longer needed or if it is to be opened in a
different file mode.
Syntax:
File_object.close()
Example:
>>> f1 = open("smapl.txt","a")
>>>f1.close()
After closing a file we can‘t perform any operation on that file. If want to do
so, we have to open the file again.
5.1.5 Reading from a File
To read the content of a file, we must open the file in reading mode.
There are three ways to read data from a text file.
1. read() : Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file.
File_object.read([n])
2. readline() : Reads a line of the file and returns in form of a string.For specified n, reads
at most n bytes. However, does not reads more than one line, even if n exceeds the length
of the line.
File_object.readline([n])
3. readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Example:
Consider the content of file sample.txt that is present in location G:\class\python\code\ as
Read Only
Read and Write
Write OnlyWrite and Read
Append Only
Append and Read
Now execute the following file reading script.
>>> f1=open("G:\class\python\code\sample.txt","r")
>>>f1.read()
'Read Only\nRead and Write\nWrite Only\nWrite and Read\nAppend Only\nAppend and
Read'
Here \n denotes next line character. If you again run the same script, you will
get empty string. Because during the first read statement itself file handler reach the end of
the file. If you read again it will return empty string
>>>f1.read()
''
So in order to take back the file handler to the beginning of the file you have
to open the file again or use seek() function. We will discuss about seek function in
upcoming section.
>>> f1=open("G:\class\python\code\sample.txt","r")
>>>f1.read(10)
'Read Only\n'
>>> f1=open("G:\class\python\code\sample.txt","r")
>>>f1.readline()
'Read Only\n'
>>> f1=open("G:\class\python\code\sample.txt","r")
>>>f1.readlines()
['Read Only\n', 'Read and Write\n', 'Write Only\n', 'Write and Read\n', 'Append Only\n',
'Append and Read']'

5.1.6 File Positions


tell():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.

seek():The seek(offset[, from]) method changes the current file position. The
offset argument indicates the number of bytes to be moved. The from argument specifiesthe
reference position from where the bytes are to be moved.

If from is set to 0, it means use the beginning of the file as the reference position
and 1 means use the current position as the reference position and if it is set to 2 then the end
of the file would be taken as the reference position. If the second argument is omitted, it also
means use the beginning of the file as the reference position.

Example:

>>> f1=open("G:\class\python\code\sample.txt","r")
>>>f1.tell()
0L
>>>f1.readline()
'Read Only\n'
>>>f1.tell()
11L
>>>f1.seek(0)
>>>f1.tell()
0L
>>>f1.seek(5)
>>>f1.tell()
5L
>>>f1.readline()
'Only\n'

5.1.7 Writing to a File


In order to write into a file we need to open it in write 'w' or append 'a'. We need
to be careful with the 'w' mode as it will overwrite into the file if it already exists. All previous
data are erased.
There are two ways to write in a file.
1. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)
2. writelines() : For a list of string elements, each string is inserted in the text file.Used to
insert multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Example:

>>> f4=open("fruit.txt","w")
>>>fruit_list=['Apple\n','Orange\n','Pineapple\n']
>>>f4.writelines(fruit_list)
>>>f4.write('Strawberry\n')
>>>f4.close()
>>> f4=open("fruit.txt","r")
>>>f4.read()
'Apple\nOrange\nPineapple\nStrawberry\n'
5.1.8 Appending to a File
Adding content at the end of a file is known as append. In order to do
appending operation, we have to open the file with append mode.
Example:
>>> f4=open('fruit.txt','a')
>>>f4.write('Banana')
>>>f4.close()
>>> f4=open('fruit.txt','r')
>>>f4.read()
'Apple\nOrange\nPineapple\nStrawberry\nBanana\n'

5.1.9 The File Object Attributes


Once a file is opened and you have one file object, you can get various
information related to that file.Here is a list of all attributes related to file object:
Attribute Description

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

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

File_object.name Returns name of the file.

File_object.softspace Returns false if space explicitly required with print, true otherwise.

5.1.10 Format Operator


The argument of write has to be a string, so if we want to put other values in a
file, we have to convert them to strings. The easiest way to do that is with str:
>>> f5=open('stringsample.txt','w')
>>>f5.write(5)
TypeError: expected a string or other character buffer object
>>>f5.write(str(5))
An alternative is to use the format operator, %. When applied to integers, %
is the modulus operator. But 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 decimal value is converted to string.
>>> run=8
>>> '%d'%run
'8'
The result is the string '8', which is not to be confused with the integer value
8.Some other format strings are.
Conversion Meaning
d Signed integer decimal.
i Signed integer decimal.
o Unsigned octal.
u Unsigned decimal.
x Unsigned hexadecimal (lowercase).
X Unsigned hexadecimal (uppercase).
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point decimal format.
F Floating point decimal format.
g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()).
s String (converts any python object using str()).
% No argument is converted, results in a "%" character in the result.
A format sequence can appear anywhere in the string, so you can embed a
value in a sentence:
>>> 'India need %d runs'%3
'India need 3 runs'
If there is more than one format sequence in the string, the second argument
has to be a tuple. Each format sequence is matched with an element of the tuple, in order.
>>> 'India need %d runs in %d balls'%(3,5)
'India need 3 runs in 5 balls'
The following example uses '%d' to format an integer, '%g' to format a
floating-point number, and '%s' to format a string:
>>> '%d %s price is %g rupees'%(5,'apple',180.50)
'5 apple price is 180.500000 rupees'
The number of elements in the tuple has to match the number of format
sequences in the string. Also, the types of the elements have to match the format sequences:
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'apple'
TypeError: %d format: a number is required, not str
In the first example, there aren‘t enough elements; in the second, the element
is the wrong type.

5.1.11 Filenames and Paths


Files are organized into directories (also called ―folders‖). Every running
program has a ―current directory‖, which is the default directory for most operations. For
example, when you open a file for reading, Python looks for it in the current directory.
The os module provides functions for working with files and directories (―os‖
stands for ―operating system‖). os.getcwd returns the name of the current directory:
>>> import os
>>>os.getcwd()
'C:\\Python27'
cwd stands for ―current working directory‖. A string like 'C:\\Python27' that
identifies a file or directory is called a path.
A simple filename, like 'stringsample.txt' is also considered a path, but it is a
relative path because it relates to the current directory.
If the current directory 'C:\\Python27', the filename 'stringsample.txt' would
refer to 'C:\\Python27\\stringsample.txt'.
A path that begins with drive letter does not depend on the current directory; it
is called an absolute path. To find the absolute path to a file, you can use os.path.abspath:
>>>os.path.abspath('stringsample.txt')
'C:\\Python27\\stringsample.txt'
os.path provides other functions for working with filenames and paths. For
example, os.path.exists checks whether a file or directory exists:
>>>os.path.exists('memo.txt')
True
If it exists, os.path.isdir checks whether it‘s a directory:
>>>os.path.isdir('memo.txt')
False
>>>os.path.isdir ('C:\\Python27')
True
Similarly, os.path.isfile checks whether it‘s a file.
os.listdir returns a list of the files (and other directories) in the given directory:
>>>cwd=os.getcwd()
>>>os.listdir(cwd)
['DLLs', 'Doc', 'include', 'infinitLoop.py', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt',
'parameter.py', 'python.exe', 'pythonw.exe', 'README.txt', 'sample.txt', 'sample2.txt',
'Scripts', 'stringsample.txt', 'swapwith third.py', 'tcl', 'Tools', 'w9xpopen.exe', 'wc.py', 'wc.pyc']
To demonstrate these functions, the following example ―walks‖ through a
directory, prints the names of all the files, and calls itself recursively on all the directories.
>>>def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
ifos.path.isfile(path):
print(path)
else:
walk(path)
>>>cwd=os.getcwd()
>>>walk(cwd)
Output:
C:\Python27\DLLs\bz2.pyd
C:\Python27\DLLs\py.ico
C:\Python27\DLLs\pyc.ico
C:\Python27\DLLs\pyexpat.pyd
C:\Python27\DLLs\select.pyd
C:\Python27\DLLs\sqlite3.dll
C:\Python27\DLLs\tcl85.dll
C:\Python27\include\abstract.h
C:\Python27\include\asdl.h
C:\Python27\include\ast.h
os.path.join takes a directory and a file name and joins them into a complete
path.
>>>os.path.join(cwd,'stringsample.txt')
'C:\\Python27\\stringsample.txt'
5.2 COMMAND LINE ARGUMENTS
It is possible to pass some values from the command line to your python
programs when they are executed. These values are called command line arguments and many
times they are important for your program especially when you want to control your program
from outside instead of hard coding those values inside the code.
The command line arguments are handled using sys module. We can access
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 nameie. script name.

Example 1
Consider the following script command_line.py

import sys
print 'There are %d arguments'%len(sys.argv)
print 'Argument are', str(sys.argv)
print 'File Name is: ', sys.argv[0]
Now run above script as follows – in Command prompt:
C:\Python27>python.exe command_line.py vinuranjith
This produce following result –
There are 3 arguments
Argument are ['command_line.py', 'vinu', 'ranjith']
File Name is: command_line.py
NOTE: As mentioned above, first argument is always script name and it is also being counted
in number of arguments. Here ‗vinu‘ and ‗ranjith‘ are extra inputs passed toprogram
through command line argument method while running python program command_line.py.
Example 2
This is a Python Program to copy the contents of one file into another. Source
and destination file names are given through command line argument while running the
program.

In order to do this we have to follow the following steps

1) Open file name with command line argument one as read mode (input file).
2) Open file name with command line argument two as write mode (output file).
3) Read each line from the input file and write it into the output file until the input file
data getsover.
4) Exit.

Program

import sys
source=open(sys.argv[1],'r')
destination=open(sys.argv[2],'w')
while(True):
new_line=source.readline()
ifnew_line=='':
break
destination.write(new_line)
source.close()
destination.close()
Now run above script as follows – in Command prompt:
C:\Python27>python.exe copy_file.py input_file.txt output_file.txt

5.3 ERRORS AND EXCEPTIONS


There are two distinguishable kinds of errors: syntax errors and exceptions.

5.3.1 Syntax Errors


Syntax errors, also known as parsing errors, are perhaps the most common kind of
complaint you get while you are still learning Python. Syntax error is an error in the syntax of a
sequence of characters or tokens that is intended to be written in python. For compiled languages, syntax
errors are detected at compile-time. A program will not compile until all syntax errors are corrected.
For interpreted languages, however, a syntax error may be detected during program execution, and an
interpreter's error messages might not differentiate syntax errors from errors of other kinds.

5.3.2 Exceptions

Even if a statement or expression is syntactically correct, it may cause an error when an attempt is
made to execute it. Errors detected during execution are called exceptions. You will soon learn how
to handle them in Python programs. Most exceptions are not handled by programs, however, and
result in error messages as shown here:
>>> 55+(5/0)
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
55+(5/0)
ZeroDivisionError: integer division or modulo by zero

>>> 5+ repeat*2
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
5+ repeat*2
NameError: name 'repeat' is not defined

>>> '5'+5
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
'5'+5
TypeError: cannot concatenate 'str' and 'int' objects

The last line of the error message indicates what happened. Exceptions come
in different types, and the type is printed as part of the message: the types in the example
are ZeroDivisionError, NameError and TypeError. The string printed as the exception type
is the name of the built-in exception that occurred. This is true for all built-in exceptions, but
need not be true for user-defined exceptions (although it is a useful convention). Standard
exception names are built-in identifiers (not reserved keywords).

The rest of the line provides detail based on the type of exception and what caused it.

The preceding part of the error message shows the context where the exception
happened, in the form of a stack traceback. In general it contains a stack traceback listing source
lines; however, it will not display lines read from standard input.

Python’s built-in exceptions lists and their meanings.

EXCEPTION NAME DESCRIPTION


Exception Base class for all exceptions
StopIteration Raised when the next() method of an iterator does not point to any object.
SystemExit Raised by the sys.exit() function.
StandardError Base class for all built-in exceptions except StopIteration and SystemExit.
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.
AttributeError Raised in case of failure of attribute reference or assignment.
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.
KeyboardInterrupt Raised when the user interrupts program execution, usually by pressing
Ctrl+c.
LookupError Base class for all lookup errors.
IndexError Raised when an index is not found in a sequence.
KeyError Raised when the specified key is not found in the dictionary.
NameError Raised when an identifier is not found in the local or global namespace.
UnboundLocalError Raised when trying to access a local variable in a function or method but no
value has been assigned to it.
EnvironmentError Base class for all exceptions that occur outside the Python environment.
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.
OSError Raised for operating system-related errors.
SyntaxError Raised when there is an error in Python syntax.
IndentationError Raised when indentation is not specified properly.
SystemError Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
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.
NotImplementedError Raised when an abstract method that needs to be implemented in an inherited
class is not actually implemented.

5.4HANDLING EXCEPTIONS

Python provides two very important features to handle any unexpected error in
your Python programs and to add debugging capabilities in them.

➢ Exception Handling:

➢ Assertions:

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

When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.

If you have some suspicious code that may raise an exception, you 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:

Here is simple syntax of try....except...else blocks −

try:
You do your operations here;
......................
exceptExceptionI:
If there is ExceptionI, then execute this block.
exceptExceptionII:
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. This is useful when the
try block contains statements that may throw different types of exceptions.

➢ You can also provide a generic except clause, which handles any exception.

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

➢ The else-block is a good place for code that does not need the try: block's protection.

Example:
This example opens a file with write mode, writes content in the file and comes
out gracefully because there is no problem at all

try:
fp = open("test_exception.txt", "w")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
fp.close()
This produces the following result:
Written successfully
Example:
This example opens a file with read mode, and tries to write the file where you
do not have write permission, so it raises an exception

try:
fp = open("test_exception.txt", "r")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
fp.close()
This produces the following result
Error: File don't have read permission

5.4.2 The except Clause with No Exceptions

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

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.

5.4.3 The except Clause with Multiple Exceptions

You 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.4.4 The try-finally Clause

You 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.
......................
You cannot use else clause as well along with a finally clause.

Example
This example opens a file with write mode, writes content in the file and comes
out gracefully because there is no problem at all

try:
fp = open("test_exception.txt", "w")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
finally:
print "Closing file"
fp.close()
This produces the following result
Written successfully
Closing file
Example
This example opens a file with read mode, and tries to write the file where you
do not have write permission, so it raises an exception

try:
fp = open("test_exception.txt", "r")
fp.write("Exception handling")
exceptIOError:
print "Error: File don\'t have read permission"
else:
print "Written successfully"
finally:
print "Closing file"
fp.close()
This produces the following result
Error: File don't have read permission
Closing file
In the above two examples, one script didn‘t raise exception and another script
raise exception. But we can see that in both cases finally block gets executed.

5.4.5 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. You capture
an exception's argument by supplying a variable in the except clause as follows −

try:
You do your operations here;
......................
exceptExceptionType, Argument:
You can print value of Argument here...
If you write the code to handle a single exception, you can have a variable
follow the name of the exception in the except statement. If you are trapping multiple
exceptions, you can have a variable follow the tuple of the exception.

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
Following is an example for a single exception

deftemp_convert(var):
try:
returnint(var)
exceptValueError, Argument:
print "The argument is not a numbers\n", Argument
temp_convert("abc")
This produces the following result
The argument is not a numbers
invalid literal for int() with base 10: 'abc'

5.4.6 Hierarchical Exceptions Handle


Exception handlers don‘t just handle exceptions if they occur immediately in the try
clause, but also if they occur inside functions that are called (even indirectly) in the try clause. For
example:

defthis_fails():
x = 1/0
try:
this_fails()
exceptZeroDivisionError, detail:
print 'Handling run-time error:', detail
This produces the following result
Handling run-time error: integer division or modulo by zero
In this example exception is raised in this_fails() function. But, because of
this_fails() function don‘t have except block exception is thrown to the caller function. As there
is a except block, it will handle the exception.

5.4.7 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
An exception can be a string, a class or an object. Most of the exceptions that
the Python core raises are classes, with an argument that is an instance of the class. Defining
new exceptions is quite easy and can be done as follows −

deffunctionName( level ):
if level < 1:
raise "Invalid level!", level
# if we raise the exception,code below to this not executed
Note: In order to catch an exception, an "except" clause must refer to the same exception
thrown either class object or simple string. For example, to capture above exception, we must
write the except clause as follows
try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...

5.4.8 Assertions in Python

An assertion is a sanity-check that you can turn on or turn off when you are
done with your testing of the program.

The easiest way to think of an assertion is to liken it to a raise-if statement (or


to be more accurate, a raise-if-not statement). An expression is tested, and if the result comes
up false, an exception is raised.

Assertions are carried out by the assert statement, the newest keyword to
Python, introduced in version 1.5.

Programmers often place assertions at the start of a function to check for valid
input, and after a function call to check for valid output.

The assert Statement


When it encounters an assert statement, Python evaluates the accompanying
expression, which is hopefully true. If the expression is false, Python raisesan
AssertionError exception.

The syntax for assert is

assert Expression[, Arguments]


If the assertion fails, Python uses ArgumentExpression as the argument for
the AssertionError. AssertionError exceptions can be caught and handled like any other
exception using the try-except statement, but if not handled, they will terminate the program
and produce a traceback.

Example

Here is a function that converts a temperature from degrees Kelvin to degrees


Fahrenheit. Since zero degrees Kelvin is as cold as it gets, the function bails out if it sees a
negative temperature

defKelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
printKelvinToFahrenheit(275)
printint(KelvinToFahrenheit(509.25))
printKelvinToFahrenheit(-7)
When the above code is executed, it produces the following result
35.6
457

Traceback (most recent call last):


File "G:/class/python/code/assertion.py", line 6, in <module>
printKelvinToFahrenheit(-7)
File "G:/class/python/code/assertion.py", line 2, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
AssertionError: Colder than absolute zero!

5.5 MODULES

A module allows you to logically organize your Python code. Grouping related
code into a module makes the code easier to understand and use. A module is a file that
contains a collection of related functions. Python has lot of built-in modules; math module is
one of them. math module provides most of the familiar mathematical functions.

Before we can use the functions in a module, we have to import it with an import statement:

>>> import math


This statement creates a module object named math. If you display the
module object, youget some information about it:

>>>math
<module 'math' (built-in)>
The module object contains the functions and variables defined in the module.
To access one of the functions, you have to specify the name of the module and the name of
the function, separated by a dot (also known as a period). This format is called dot notation.
>>>math.log10(200)
2.3010299956639813
>>>math.sqrt(10)
3.1622776601683795
Math module have functions like log(), sqrt(), etc… In order to know what are
the functions available in particular module, we can use dir() function after importing particular
module. Similarly if we want to know detail description about a particular module or function
or variable means we can use help() function.
Example
>>> import math
>>>dir(math)
[' doc ', ' name ', ' package ', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh',
'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor',
'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
>>>help(pow)
Help on built-in function pow in module builtin :

pow(...)
pow(x, y[, z]) -> number

With two arguments, equivalent to x**y. With three arguments,


equivalent to (x**y) % z, but may be more efficient (e.g. for longs).

5.5.1Writing Modules
Any file that contains Python code can be imported as a module. For example,
suppose you have a file named addModule.py with the following code:
def add(a, b):
result = a + b
print(result)
add(10,20)
If you run this program, it will add 10 and 20 and print 30. We can import it like this:
>>> import addModule
30
Now you have a module object addModule
>>>addModule
<module 'addModule' from 'G:/class/python/code\addModule.py'>
The module object provides add():
>>>addModule.add(120,150)
270
So that‘s how you write modules in Python.
The only problem with this example is that when you import the module it
runs the test code at the bottom. Normally when you import a module, it defines new functions
but it doesn‘t run them.
Programs that will be imported as modules often use the following idiom:
if name == ' main ':
add(10,20)
name is a built-in variable that is set when the program starts. If the
program is running as a script, name has the value ' main '; in that case, the test code runs.
Otherwise, if the module is being imported, the test code is skipped. Modify addModule.py file
as given below.
def add(a, b):
result = a + b
print(result)
if name == ' main ':
add(10,20)
Now while importing addModule test case is not running
>>> import addModule
name has module name as its value when it is imported. Warning: If you
import a module that has already been imported, Python does nothing. It does not re-read the
file, even if it has changed. If you want to reload a module, you can use the built-in function
reload, but it can be tricky, so the safest thing to do is restart the interpreter and then import the
module again.

5.6 PACKAGES

Packages are namespaces which contain multiple packages and modules


themselves. They are simply directories, but with a twist.
Each package in Python is a directory which must contain a special file called
init .py. This file can be empty, and it indicates that the directory it contains is a Python
package, so it can be imported the same way a module can be imported.

If we create a directory called sample_package, which marks the package


name, we can then create a module inside that package called sample_module. We also must
not forget to add the init .py file inside the sample_package directory.

To use the module sample_module, we can import it in two ways:


>>> import sample_package.sample_module
or:
>>>fromsample_package import sample_module
In the first method, we must use the sample_package prefix whenever we access the
module sample_module. In the second method, we don't, because we import the module to our
module's namespace.

The init .py file can also decide which modules the package exports as the API, while keeping
other modules internal, by overriding the all variable, like so:

init .py:
all = ["sample_module"]

5.7 WORD COUNT

Example.
Following program print each word in the specified file occurs how many times.
import sys
defword_count(file_name):
try:
file=open(file_name,"r")
wordcount={}
entier_words=file.read().split()
for word in entier_words:
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
file.close();
print ("%-30s %s " %('Words in the File' , 'Count'))
for key in wordcount.keys():
print ("%-30s %d " %(key , wordcount[key]))
exceptIOError:
print ("No file found with name %s" %file_name)
fname=raw_input("Enter New File Name:")
word_count(fname)

try:
word_count(sys.argv[1])
exceptIndexError:
print("No file name passed as command line Argument")
fname=raw_input("Enter File Name:")
word_count(fname)
Content of a sample file word_count_input.txt is:
word count is the program which count each word in file appears how many times.

This produces the following result


c:\Python27>python wordcount1.py
No file name passed as command line Argument
Enter File Name:word_count_input
No file found with name word_count_input
Enter New File Name:word_count_input.txt
Words in the File Count
count 2
word 2
file 1
many 1
is 1
in 1
times 1
how 1
program 1
which 1
each 1
the 1
appears 1
Above programshows the file handling with exception handling andcommand
line argument.While running, if you give command line like below, it will readthe text file
with the name, that is specifies by command line argument one and calculate thecount of each
word and print it.
c:\Python27>python wordcount1.py word_count_input.txt
While running, if you give command line like below(ie, no command line
argument), On behalf of exception handling it will ask for file name and then do the same
operation on the newly entered file.
c:\Python27>python wordcount1.py
Program also handle file not found exception, if wrong file name is entered. It
will ask for new file name to enter and proceed.
Example.
Following program counts number of words in the given file.
import sys
defword_count(file_name):
count=0
try:
file=open(file_name,"r")
entier_words=file.read().split()
for word in entier_words:
count=count+1
file.close();
print ("%s File have %d words" %(file_name,count))
exceptIOError:
print ("No file found with name %s" %file_name)
fname=raw_input("Enter New File Name:")
word_count(fname)

try:
word_count(sys.argv[1])
exceptIndexError:
print("No file name passed as command line Argument")
fname=raw_input("Enter File Name:")
word_count(fname)
This produces the following result
c:\Python27>python wordcount2.py
No file name passed as command line Argument
Enter File Name:word_count_input
No file found with name word_count_input
Enter New File Name:word_count_input.txt
word_count_input.txt File have 15 words
Above programalso shows the file handling with exception handling and
command line argument.While running, if you give command line like below, it will read
the text file with the name, that is specifies by command line argument one and count
number of word present in it and print it.
c:\Python27>python wordcount2.py word_count_input.txt
While running, if you give command line like below ( ie, no command line
argument), On behalf of exception handling it will ask for file name and then do the same
word counting operation on the newly entered file.
c:\Python27>python wordcount2.py
Program also handle file not found exception, if wrong file name is entered. It
will ask for new file name to enter and proceed.

5.8 INTRODUCTION TO NUMPY


• NumPy is a Python library used for working with arrays.
• It also has functions for working in domain of linear algebra, fourier transform, and
matrices.
• NumPy was created in 2005 by Travis Oliphant. It is an open source project and you can
use it freely.
• NumPy stands for Numerical Python.
Why use Numpy?
• In Python we have lists that serve the purpose of arrays, but they are slow to process.
• NumPy aims to provide an array object that is up to 50x faster than traditional Python
lists.
• The array object in NumPy is called ndarray, it provides a lot of supporting functions
that make working with ndarray very easy.
• Arrays are very frequently used in data science, where speed and resources are very
important.
Why is Numpy faster than Lists?
• NumPy arrays are stored at one continuous place in memory unlike lists, so processes
can access and manipulate them very efficiently.
• This behavior is called locality of reference in computer science.
• This is the main reason why NumPy is faster than lists. Also it is optimized to work with
latest CPU architectures.
Which language is Numpy written in?
NumPy is a Python library and is written partially in Python, but most of the parts that require
fast computation are written in C or C++.
Where is the Numpy codebase?
• The source code for NumPy is located at this github
repository https://github.com/numpy/numpy
• github: enables many people to work on the same codebase.
NumPy getting started
• If you have Python and PIP already installed on a system, then installation of NumPy is
very easy.
• Install it using this command:
C:\users\Your Name>pip install numpy
• If this command fails, then use a python distribution that already has NumPy installed
like, Anaconda, Spyder etc.
Import NumPy
• Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
• Now NumPy is imported and ready to use.
Example
import numpy
arr = numpy.array([1, 2, 3, 4, 5])
print(arr)
NumPy as np
• NumPy is usually imported under the np alias.
• In Python, alias are an alternate name for referring to the same thing.
• Create an alias with the as keyword while importing:
import numpy as np
• Now the NumPy package can be referred to as np instead of numpy.
Example
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Checking NumPy Version
The version string is stored under __version__ attribute.
Example
import numpy as np
print(np.__version__)

5.9 INTRODUCTION TO MATPLOTLIB


• Matplotlib is a low-level graph plotting library in Python that serves as a visualization
utility
• Matplotlib was created by John D.Hunter
• Matplotlib is open source and we can use it freely
• Matplotlib is mostly written in Python, a few segments are written in C, Objective – C
and Javascript for Platform compatibility
Where is the Matplotlib Codebase?
The source code for Matplotlib is located at this github
repository https://github.com/matplotlib/matplotlib
Installation of Matplotlib
• If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.
• Install it using this command:
C:\Users\Your Name>pip install matplotlib
• If this command fails, then use a python distribution that already has Matplotlib
installed, like Anaconda, Spyder etc.
Import Matplotlib
• Once Matplotlib is installed, import it in your applications by adding
the import module statement:
import matplotlib
• Now Matplotlib is imported and ready to use:
Checking Matplotlib Version
The version string is stored under __version__ attribute.
Example
import matplotlib
print(matplotlib.__version__)

5.10 COPY FILE

This is a Python Program to copy the contents of one file into another. In order to perform
the copying operation we need to follow the following steps.
1. Open source file in read mode.
2. Open destination file in write mode.
3. Read each line from the input file and write it into the output file.
4. Exit.
Also we include command line argument for passing source and destination file names to
program. Also exception handling is used to handle exception that occurs when dealing with
files.
import sys
def copy(src,dest):
try:
source=open(src,'r')
destination=open(dest,'w')
while(True):
new_line=source.readline()
ifnew_line=='':
break
destination.write(new_line)
source.close()
destination.close()
exceptIOError:
print ("Problem with Source or Destination File Name ")
source_name=raw_input("Enter New Source File Name:")
destination_name=raw_input("Enter New Destination File Name:")
copy(source_name,destination_name)
try:
copy(sys.argv[1],sys.argv[2])
exceptIndexError:
print("Insufficent Command line argument!")
source_name=raw_input("Enter Source File Name:")
destination_name=raw_input("Enter Destination File Name:")
copy(source_name,destination_name)
finally:
print("Copying Done.....")
This produces the following result
C:\Python27>python copy_file_exception.py input_file.txt
Insufficent Command line argument!
Enter Source File Name:input_file.tx
Enter Destination File Name:output_file.txt
Problem with Source or Destination File Name
Enter New Source File Name:input_file.txt
Enter New Destination File Name:output_file.txt
Copying Done.....

You might also like