0% found this document useful (0 votes)
23 views56 pages

Py Unit - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views56 pages

Py Unit - 5

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

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 special
formatting 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.
5. 2 Problem Solving and Python Programming

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.1File 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 has to 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.
Files , Modules and Packages 5.3

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.
5. 4 Problem Solving and Python Programming

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.
Files , Modules and Packages 5.5

>>> 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
specifies the 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
5. 6 Problem Solving and Python Programming

>>>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.
4. write() : Inserts the string str1 in a single line in the text file.
File_object.write(str1)

5. 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.
Files , Modules and Packages 5.7

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.
Returns false if space explicitly required with print,
File_object.softspace
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.
5. 8 Problem Solving and Python Programming

>>> 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.
Same as “e” if exponent is greater than -4 or less than precision,
g
“f” otherwise.
Same as “E” if exponent is greater than -4 or less than precision,
G
“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’
Files , Modules and Packages 5.9

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.
5. 10 Problem Solving and Python Programming

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’.
>>>os.path.abspath(‘stringsample.txt’)
‘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 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.
Files , Modules and Packages 5.11

>>>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.
5. 12 Problem Solving and Python Programming

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 to program through command line argument method while running python
program command_line.py.
This is a Python Program to copy the contents of one file into another. Sourceand
destination file names are given through command line argument while running the
program.
Example : 2
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.
Files , Modules and Packages 5.13

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:
5. 14 Problem Solving and Python Programming

>>> 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.
Files , Modules and Packages 5.15

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


Exception Name Description

Exception Base class for all exceptions


Raised when the next() method of an iterator does not
StopIteration
point to any object.
SystemExit Raised by the sys.exit() function.
Base class for all built-in exceptions except StopIteration
StandardError
and SystemExit.
ArithmeticError Base class for all errors that occur for numeric calculation.
Raised when a calculation exceeds maximum limit for a
OverflowError
numeric type.
FloatingPointError Raised when a floating point calculation fails.
Raised when division or modulo by zero takes place for all
ZeroDivisionError
numeric types.
AssertionError Raised in case of failure of the Assert statement.

AttributeError Raised in case of failure of attribute reference or assignment.


Raised when there is no input from either the raw_input()
EOFError
or input() functionand the end of file is reached.
ImportError Raised when an import statement fails.
Raised when the user interrupts program execution,
KeyboardInterrupt
usually by pressingCtrl+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.
Raised when an identifier is not found in the local or global
NameError
namespace.
Raised when trying to access a local variable in a function
UnboundLocalError
or method but novalue has been assigned to it.
5. 16 Problem Solving and Python Programming

Base class for all exceptions that occur outside the Python
EnvironmentError
environment.
Raised when an input/ output operation fails, such as the
IOError print statement orthe 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.


Raised when the interpreter finds an internal problem,
SystemError but when this error isencountered the Python interpreter
does not exit.
Raised when Python interpreter is quit by using the sys.
SystemExit exit() function. If nothandled in the code, causes the
interpreter to exit.
Raised when an operation or function is attempted that is
TypeError
invalid for thespecified data type.
Raised when the built-in function for a data type has the
ValueError valid type ofarguments, but the arguments have invalid
values specified.
Raised when a generated error does not fall into any
RuntimeError
category.
Raised when an abstract method that needs to be
NotImplemented
implemented in an inherited class is not actually
Error
implemented.

5. 4 Handling 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:
Files , Modules and Packages 5.17

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.
5. 18 Problem Solving and Python Programming

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
Files , Modules and Packages 5.19

5.4.2The 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.3The 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 “
5. 20 Problem Solving and Python Programming

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
Files , Modules and Packages 5.21

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
5. 22 Problem Solving and Python Programming

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.
Files , Modules and Packages 5.23

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.
5. 24 Problem Solving and Python Programming

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 raises
an 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)
Files , Modules and Packages 5.25

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
5. 26 Problem Solving and Python Programming

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 add Module


Files , Modules and Packages 5.27

>>>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
add Module.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. 28 Problem Solving and Python Programming

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:
Files , Modules and Packages 5.29

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
5. 30 Problem Solving and Python Programming

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
s

Above program 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 calculate
the count 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.
Files , Modules and Packages 5.31

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 program also 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.
5. 32 Problem Solving and Python Programming

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 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()
Files , Modules and Packages 5.33

exceptIOError:
print (“Problem with Source or Destination File Name “)
source_name=raw_input(“Enter New Source File Name:”)
destination_name=raw_input(“Enter NewDestination 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.....

Sample Programs
Exercise : 1 with Solution
Write a Python program to read an entire text file.
Sample Solution:-
Python Code:
Contain of text.txt
def file_read(fname):
txt = open(fname)
print(txt.read())
file_read(‘test.txt’)
5. 34 Problem Solving and Python Programming

Modules
Sample Output:
Welcome to w3resource.com.
Append this text.Append this text.Append this text.
Append this text.
Append this text.
Append this text.
Append this text.

Exercise : 2 with Solution


Write a Python program to read first n lines of a file.
Sample Solution:
Python Code:
def file_read_from_head(fname, nlines):
from itertools import islice
with open(fname) as f:
for line in islice(f, nlines):
print(line)
file_read_from_head(‘test.txt’,2)

Exercise : 3 with Solution


Write a Python program to append text to a file and display the text.
Sample Solution:-
Python Code:
def file_read(fname):
from itertools import islice
with open(fname, “w”) as myfile:
myfile.write(“Python Exercises\n”)
myfile.write(“Java Exercises”)
txt = open(fname)
print(txt.read())
file_read(‘abc.txt’)
Files , Modules and Packages 5.35

Exercise : 4 with Solution


Write a Python program to read last n lines of a file.
Sample Solution:-
Python Code:
import sys
import os
def file_read_from_tail(fname,lines):
bufsize = 8192
fsize = os.stat(fname).st_size
iter = 0
with open(fname) as f:
if bufsize > fsize:
bufsize = fsize-1
data = []
while True:
iter +=1
f.seek(fsize-bufsize*iter)
data.extend(f.readlines())
if len(data) >= lines or f.tell() == 0:
print(‘’.join(data[-lines:]))
break
file_read_from_tail(‘test.txt’,2)
5. 36 Problem Solving and Python Programming
Files , Modules and Packages 5.37

Exercise : 5 with Solution


Write a Python program to read a file line by line and store it into a list.
Sample Solution:-
Python Code:
def file_read(fname):
with open(fname) as f:
#Content_list is the list that contains the read lines.
content_list = f.readlines()
print(content_list)
file_read(\’test.txt\’)

Exercise : 6 with Solution


Write a Python program to read a file line by line store it into a variable.
Sample Solution:-
Python Code:
5. 38 Problem Solving and Python Programming

def file_read(fname):
with open (fname, “r”) as myfile:
data=myfile.readlines()
print(data)
file_read(‘test.txt’)

What is Python Module?


Python module is but a piece of code.
Exiting the interpreter destroys all functions and variables we created. But
when we want a longer program, we create a script.
With Python, we can put such definitions in a file, and use them in a script, or
in an interactive instance of the interpreter. Such a file is a module.
If you face any difficulty in article on Python modules, ask us in comments.
In essence, a module is a file that contains Python statements and definitions.
A Python modules looks like this:
calc.py
How to Create Python Modules?
Let’s create a Python modules ‘calc’.
Microsoft Windows [Version 10.0.16299.309]
Files , Modules and Packages 5.39

(c) 2017 Microsoft Corporation. All rights reserved.


C:\Users\lifei>cd Desktop
C:\Users\lifei\Desktop>mkdir calc
C:\Users\lifei\Desktop>cd calc
C:\Users\lifei\Desktop\calc>echo >__init__.py
C:\Users\lifei\Desktop\calc>echo >calc.py
C:\Users\lifei\Desktop\calc>
And this is what we put inside the module calc.py:
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
def exp(a,b):
return a**b
def floordiv(a,b):
return a//b

Also, calc is a package we create, and we place __init__.py inside it (Refer to


Python Packages).
How can we Import Modules in Python?
Now, to import Python modules, we first get to the Desktop in Python.
>>> import os
>>> os.chdir(‘C:\\Users\\lifei\\Desktop\\calc’)
>>> import calc
>>>

To find the name of this module, we can use the __name__ attribute.
>>> calc.__name__
5. 40 Problem Solving and Python Programming

Output
‘calc’
We can now use functions from this module:
We can also assign one of these functions a name:
>>> fd=calc.floordiv
>>> fd(5.5,4)

Output
1.0
>>> fd(9,4)

Output
2
>>> type(fd(9,4))

Output
<class ‘int’>
>>> type(fd(5.5,4))

Output
<class ‘float’>

More on Python Modules and Importing


Python modules may contain anything from executable statements to function
definitions. Such statements initialize the module. Hence, they execute only once,
when we import the module.
However, they also run if we execute the file as a script. Each module uses its
own private symbol table globally for all of its functions.
So, its author can use global variables in the module without worrying that
they will accidentally clash with a user’s global variables.
A module can always import other modules in Python. In fact, we can place
import statements at the beginning of a module/script, but we don’t ‘need’ to.
This places the imported module’s name in the importing module’s symbol
table.
Files , Modules and Packages 5.41

We can also selectively import functions from a Python modules:


>>> from calc import div as d,floordiv as fd
>>> d(9,4)

Output
2.25
>>> fd(9,4)

Output
2
We can also import all from a module:
>>> from calc import *
>>> floordiv(9,4)

Output
2

This will import all names other than those beginning with an underscore(_).
However, we disparage this use, as it makes for poorly readable code.
We can also import a module under an alias.
>>> import calc as cal
>>> cal.sub

Output
<function sub at 0x0655CC90>
How to Execute Python Modules as Scripts?
Look at the following code:
5. 42 Problem Solving and Python Programming

def add(a,b):
print(a+b)
def sub(a,b):
print(a-b)
def mul(a,b):
print(a*b)
def div(a,b):
print(a/b)
def exp(a,b):
print(a**b)
def floordiv(a,b):
print(a//b)
if __name__ == “__main__”:
import sys
if int(sys.argv[1])==1:
add(int(sys.argv[2]),int(sys.argv[3]))
elif int(sys.argv[1])==2:
sub(int(sys.argv[2]),int(sys.argv[3]))

These last few lines let us use the sys module to deal with command line
arguments. To execute subtraction, this is what we type in the command prompt:
C:\Users\lifei\Desktop\calc>python calc.py 2 3 4
-1

This way, you can complete the code for other operations as well. Hence, we’ve
created a script. But we can also import this normally like a module:
>>> import calc
>>>

We may want to run a module as a script for testing purposes.


Any Doubt yet in Python Modules? Please Comment.
Python Module Search Path
Whenever we import Python modules, say eggs, the interpreter searches a
built-in version. If not found, it searches for a file named eggs.py under a list of
directories given by variable sys.path.
Files , Modules and Packages 5.43

This variable is initialized from the following locations:


The directory holding the input script (or the current directory, in case no file
is specified).
PYTHONPATH (a list of directory names, with the same syntax as the shell
variable PATH).
The installation-dependent default.
Once initialized, a Python program may modify sys.path.
Compiled Python Files
In an attempt to speed up loading a module, Python will cache each module’s
compiled version in the __pycache__ directory. It does so under the name module.
version.pyc.
Here, the version encodes the compiled file’s format. For instance, under
CPython 3.3, we’ll have eggs.py as __pycache__/eggs.cpython-33.pyc.
This allows compiled modules from different Python versions and releases to
coexist.
These compiled modules are platform-independent. If the compiled version is
out of date, Python recompiles it automatically.
Python Standard Modules
And like we’ve always said, Python ships with a library of standard Python
modules. While some of them are built into the interpreter, we can create our own.
The standard ones lend us extra functionality, in turn reducing the need to
code too much. Other times, they provide efficiency to a programmer, in cases like
providing access to operating system primitives, the likes of system calls.
The module sys is built into every Python interpreter. However, some modules
are only available to certain operating platforms.
For instance, the winreg module is only available to Windows programmers.
The sys module will also tell you which version of Python you are using.
>>> import sys
>>> sys.version

Output
‘3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 07:18:10) [MSC v.1900 32 bit
(Intel)]’
5. 44 Problem Solving and Python Programming

Python dir() Function


The dir() is a built-in function that returns a sorted list of all the names that a
Python modules defines.
>>> dir(sys)

Output
[‘__displayhook__’, ‘__doc__’, ‘__excepthook__’, ‘__interactivehook__’, ‘__
loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘__stderr__’, ‘__stdin__’,
‘__stdout__’, ‘_clear_type_cache’, ‘_current_frames’, ‘_debugmallocstats’,
‘_enablelegacywindowsfsencoding’, ‘_getframe’, ‘_home’, ‘_mercurial’, ‘_
xoptions’, ‘api_version’, ‘argv’, ‘base_exec_prefix’, ‘base_prefix’, ‘builtin_
module_names’, ‘byteorder’, ‘call_tracing’, ‘callstats’, ‘copyright’, ‘displayhook’,
‘dllhandle’, ‘dont_write_bytecode’, ‘exc_info’, ‘excepthook’, ‘exec_prefix’,
‘executable’, ‘exit’, ‘flags’, ‘float_info’, ‘float_repr_style’, ‘get_asyncgen_
hooks’, ‘get_coroutine_wrapper’, ‘getallocatedblocks’, ‘getcheckinterval’,
‘getdefaultencoding’, ‘getfilesystemencodeerrors’, ‘getfilesystemencoding’,
‘getprofile’, ‘getrecursionlimit’, ‘getrefcount’, ‘getsizeof’, ‘getswitchinterval’,
‘gettrace’, ‘getwindowsversion’, ‘hash_info’, ‘hexversion’, ‘implementation’,
‘int_info’, ‘intern’, ‘is_finalizing’, ‘last_traceback’, ‘last_type’, ‘last_value’,
‘maxsize’, ‘maxunicode’, ‘meta_path’, ‘modules’, ‘path’, ‘path_hooks’,
‘path_importer_cache’, ‘platform’, ‘prefix’, ‘set_asyncgen_hooks’, ‘set_
coroutine_wrapper’, ‘setcheckinterval’, ‘setprofile’, ‘setrecursionlimit’,
‘setswitchinterval’, ‘settrace’, ‘stderr’, ‘stdin’, ‘stdout’, ‘thread_info’, ‘version’,
‘version_info’, ‘warnoptions’, ‘winver’]
>>> for i in dir(calc): print(i)

Output
__builtins__
__cached__
__doc__
__file__
__loader__
__name__
__package__
Files , Modules and Packages 5.45

__spec__
add
div
exp
floordiv
mul
sub

And without any arguments, dir() returns a lilst of the names that we have
defined currently.
>>> dir()

Output

[‘__annotations__’, ‘__builtins__’, ‘__doc__’, ‘__loader__’, ‘__name__’, ‘__


package__’, ‘__spec__’, ‘add’, ‘cal’, ‘calc’, ‘div’, ‘exp’, ‘floordiv’, ‘i’, ‘mul’, ‘os’, ‘sub’,
‘sys’]

To get a list of built-in functions and variables, we do the following, instead:


>>> import builtins
>>> dir(builtins)

Output
[‘ArithmeticError’, ‘AssertionError’, ‘AttributeError’, ‘BaseException’,
‘BlockingIOError’, ‘BrokenPipeError’, ‘BufferError’, ‘BytesWarning’,
‘ChildProcessError’, ‘ConnectionAbortedError’, ‘ConnectionError’,
‘ConnectionRefusedError’, ‘ConnectionResetError’, ‘DeprecationWarning’,
‘EOFError’, ‘Ellipsis’, ‘EnvironmentError’, ‘Exception’, ‘False’,
‘FileExistsError’, ‘FileNotFoundError’, ‘FloatingPointError’,
‘FutureWarning’, ‘GeneratorExit’, ‘IOError’, ‘ImportError’, ‘ImportWarning’,
‘IndentationError’, ‘IndexError’, ‘InterruptedError’, ‘IsADirectoryError’,
‘KeyError’, ‘KeyboardInterrupt’, ‘LookupError’, ‘MemoryError’,
‘ModuleNotFoundError’, ‘NameError’, ‘None’, ‘NotADirectoryError’,
‘NotImplemented’, ‘NotImplementedError’, ‘OSError’, ‘OverflowError’,
5. 46 Problem Solving and Python Programming

‘PendingDeprecationWarning’, ‘PermissionError’, ‘ProcessLookupError’,


‘RecursionError’, ‘ReferenceError’, ‘ResourceWarning’, ‘RuntimeError’,
‘RuntimeWarning’, ‘StopAsyncIteration’, ‘StopIteration’, ‘SyntaxError’,
‘SyntaxWarning’, ‘SystemError’, ‘SystemExit’, ‘TabError’, ‘TimeoutError’,
‘True’, ‘TypeError’, ‘UnboundLocalError’, ‘UnicodeDecodeError’,
‘UnicodeEncodeError’, ‘UnicodeError’, ‘UnicodeTranslateError’,
‘UnicodeWarning’, ‘UserWarning’, ‘ValueError’, ‘Warning’, ‘WindowsError’,
‘ZeroDivisionError’, ‘_’, ‘__build_class__’, ‘__debug__’, ‘__doc__’, ‘__import__’,
‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘abs’, ‘all’, ‘any’, ‘ascii’, ‘bin’,
‘bool’, ‘bytearray’, ‘bytes’, ‘callable’, ‘chr’, ‘classmethod’, ‘compile’, ‘complex’,
‘copyright’, ‘credits’, ‘delattr’, ‘dict’, ‘dir’, ‘divmod’, ‘enumerate’, ‘eval’, ‘exec’,
‘exit’, ‘filter’, ‘float’, ‘format’, ‘frozenset’, ‘getattr’, ‘globals’, ‘hasattr’, ‘hash’,
‘help’, ‘hex’, ‘id’, ‘input’, ‘int’, ‘isinstance’, ‘issubclass’, ‘iter’, ‘len’, ‘license’, ‘list’,
‘locals’, ‘map’, ‘max’, ‘memoryview’, ‘min’, ‘next’, ‘object’, ‘oct’, ‘open’, ‘ord’,
‘pow’, ‘print’, ‘property’, ‘quit’, ‘range’, ‘repr’, ‘reversed’, ’round’, ‘set’, ‘setattr’,
‘slice’, ‘sorted’, ‘staticmethod’, ‘str’, ‘sum’, ‘super’, ‘tuple’, ‘type’, ‘vars’, ‘zip’]

This was all on Python modules. Hope the Python Modules article was
informative.
Python Interview Questions on Modules
1. What is module in Python? Explain with example.
2. Explain the purpose for using Python modules.
3. How many modules are there in Python?
4. How to install and open a Python module?
5. Where are Python modules stored?
Conclusion
While this is all about Python modules, we suggest you should also read about
Packages in Python. Then, maybe you should switch to Packages vs Modules.
Packages
Python Packages Tutorial – How to Create Your Own Package
What are Python Packages?
In our computer systems, we store our files in organized hierarchies. We don’t
Files , Modules and Packages 5.47

store them all in one location. Likewise, when our programs grow, we divide it into
packages.
In real-life projects, programs are much larger than what we deal with in our
journey of learning Python. A package lets us hold similar modules in one place.
Like a directory may contain subdirectories and files, a package may contain
sub-packages and modules. We have been using modules a lot in the previous lessons.
Remember math, os, and collections? Those were all modules that ship with
Python officially. We will discuss the difference between a module and a package in
our next lesson.
But for now, let’s dive into the world of Python packages.
Structure of Python Packages
As we discussed, a package may hold other Python packages and modules. But
what distinguishes a package from a regular directory? Well, a Python package must
have an __init__.py file in the directory.
You may leave it empty, or you may store initialization code in it. But if your
directory does not have an __init__.py file, it isn’t a package; it is just a directory
with a bunch of Python scripts. Leaving __init__.py empty is indeed good practice.
Take a look at the following structure for a game:
5. 48 Problem Solving and Python Programming

Python Packages Module Structure


Here, the root package is Game. It has sub packages Sound, Image, and Level,
and file __init__.py. Sound further has modules load, play, and pause, apart from
file __init__.py.
Image has modules open, change, and close, apart from __init__.py. Finally,
Level has modules start, load, and over, apart from __init__.py.
How to Import Modules from Packages in Python?
A Python package may contain several modules. To import one of these into
your program, you must use the dot operator(.)
In the above example, if you want to import the load module from subpackage
sound, we type the following at the top of our Python file:
import Game.Sound.load
Note that we don’t type the extension, because that isn’t what we refer to the
module as. The subpackage Level has a module named load too, but there is no clash
here.
This is because we refer to the module by its fully qualified name.
To escape having to type so much every time we needed to use the module, we
could also import it under an alias:
import Game.Sound.load as loadgame
(If you’re working the interpreter, you may also do the following:
loadgame=Game.Sound.load
This works equally fine.)
Alternatively, you could do:
from Game.Sound import load
Now, if the Sound subpackage has a function volume_up(), we call it this way:
loadgame.volume_up(7)
If we imported this way:
from Game.Sound.load import volume_up() as volup
We could call the function simply, without needing to use a full qualifier:
volup(7)
But this isn’t recommended, as this may cause names in a namespace to clash.
Files , Modules and Packages 5.49

Further Notes
When you import a package, only the modules directly under it are imported.
An import does not import the sub packages.
>>> import one
>>> one.two

Output
Traceback (most recent call last):File “<pyshell#488>”, line 1, in <module>one.
two.evenoddAttributeError: module ‘one’ has no attribute ‘two’
Also note that if you want to check where your Python packages are being
created, your path will look something like this:
C:\Users\lifei\AppData\Local\Programs\Python\Python36-32\Lib\site-
packages
How to Create Your Own Python Package?
Now, on to the most interesting part. Like we said, Python packages are
nothing but a dictionary with sub-packages and modules, and an __init__.py file.
In our example, this is the hierarchy we create:

How to Create Your Own Python Package


This is what we have in evenodd.py:
def check():
a=int(input(‘Enter a number’))
if a%2==0: print(“Even”)
else: print(“Odd”)

Also, we keep each __init__.py empty.


Now, we import and use it this way:
5. 50 Problem Solving and Python Programming

>>> from one.two.evenodd import check as check


>>> check()

Output
Enter a number7
Odd
>>> check()

Output
Enter a number0
Even

5. 9 With Answers
Two Marks Questions
1. What is module and package in Python?
In Python, module is the way to structure program. Each Python program file
is a module, which imports other modules like objects and attributes.
2. Explain how can you access a module written in Python from C?
We can access a module written in Python from C by following method,
Module ==PyImport_ImportModule(–<modulename>‖);

3. Mention five benefits of using Python?


 Python comprises of a huge standard library for most Internet platforms
like Email, HTML, etc.
 Python does not require explicit memory management as the interpreter
itself
 allocates the memory to new variables and free them
 automatically Provide easy readability due to use of square brackets
 Easy-to-learn for beginners
 Having the built-in data types saves programming time and effort from
declaring variables
4. How to open a new file in Python?
Opening a file creates a file object. In this example, the variable f refers to the
new file object.
Files , Modules and Packages 5.51

>>> f = open(“test.dat”,”w”)
>>> print f<open file _test.dat‘, mode _w‘ at fe820>

The open function takes two arguments. The first is the name of the file, and
the second is the mode. Mode “w” means that we are opening the file for writing.
5. Explain how the write method works on a file.
>>> f.write(“Now is the time”)
>>> f.write(“to close the file”)

Closing the file tells the system that we are done writing and makes the file
available for reading:
>>> f.close()
6. Which method is used to read the contents of a file which is already
created?
The read method reads data from the file. With no arguments, it reads the
entire contents of the file:
>>> text = f.read()
>>> print text

Now is the timeto close the file


7. What is a text file? Give an example for a text file.
A text file is a file that contains printable characters and whitespace,organized
into lines separated by newline characters.
To demonstrate, we‘ll create a text file with three lines of text separated by
newlines:
>>> f = open(“test.dat”,”w”)
>>> f.write(“line one\nline two\nline three\n”)
>>> f.close()

8. What is the difference between break and continue statement?


The break statement is new. Executing it breaks out of the loop; the flow of
execution moves to the first statement after the loop.
The continue statement ends the current iteration of the loop, but continues
looping.The flow of execution moves to the top of the loop, checks the condition,
and proceeds accordingly.
5. 52 Problem Solving and Python Programming

9. What is meant by directory? How and where is it useful?


When we want to open a file somewhere else, you have to specify the pathto the
file, which is the name of the directory (or folder) where the file is located:
>>> f = open(“/usr/share/dict/words”,”r”)
>>
>
printf.readline() Aarhus

This example opens a file named words that resides in a directory named dict,
which resides in share, which resides in usr, which resides in the top-level
directory of the system, called .
10. Explain pickling and how import pickle works.
Pickling is so called because it –preserves– data structures. The pickle module
contains the necessary commands. To use it, import pickle and then open the
file in the usual way:
>>> import pickle
>>> f = open(“test.pck”,”w”)

11. What is an exception? Explain with few examples.


Whenever a runtime error occurs, it creates an exception. Usually,the program
stops and Python prints an error message.
Forexample,
dividing by zero creates an exception:
>>> print 55/0
ZeroDivisionError: integer division or modulo So does accessing a nonexistent
list item:
>>> a = []
>>> print a[5]
12. What is module and package in Python?
In Python, module is the way to structure program. Each Python program file
is a module, which imports other modules like objects and attributes.
13. Explain how can you access a module written in Python from C?
We can access a module written in Python from
C by following method,Module ==PyImport_ImportModule(–<modulename>‖);
Files , Modules and Packages 5.53

14. Mention five benefits of using Python?


 Python comprises of a huge standard library for most Internet platforms
like Email, HTML, etc.
 Python does not require explicit memory management as the interpreter
itself
 allocates the memory to new variables and free them
 automatically Provide easy readability due to use of square brackets
 Easy-to-learn for beginners
 Having the built-in data types saves programming time and effort from
declaring variables
15. How to open a new file in Python?
Opening a file creates a file object. In this example, the variable f refers to the
new file object.
>>> f = open(“test.dat”,”w”)
>>> print f<open file _test.dat‘, mode _w‘ at fe820>

The open function takes two arguments. The first is the name of the file, and the
second is the mode. Mode “w” means that we are opening the file for writing.
16. Explain how the write method works on a file.
>>> f.write(“Now is the time”)
>>> f.write(“to close the file”)

Closing the file tells the system that we are done writing and makes the file
available for reading:
>>> f.close()

17. Which method is used to read the contents of a file which is already
created?
The read method reads data from the file. With no arguments, it reads the
entire contents of the file:
>>> text = f.read()
>>> print text

Now is the time to close the file


5. 54 Problem Solving and Python Programming

18. What is a text file? Give an example for a text file.


A text file is a file that contains printable characters and whitespace,organized
into lines separated by newline characters.
To demonstrate, we‘ll create a text file with three lines of text separated by
newlines:
>>> f = open(“test.dat”,”w”)
>>> f.write(“line one\nline two\nline three\n”)
>>> f.close()

19. What is the difference between break and continue statement?


The break statement is new. Executing it breaks out of the loop; the flow of
execution moves to the first statement after the loop.
The continue statement ends the current iteration of the loop, but continues
looping.The flow of execution moves to the top of the loop, checks the condition,
and proceeds accordingly.
20. What is meant by directory? How and where is it useful?
When we want to open a file somewhere else, you have to specify the pathto the
file, which is the name of the directory (or folder) where the file is located:
>>> f = open(“/usr/share/dict/words”,”r”)
>>
>
printf.readline() Aarhus

This example opens a file named words that resides in a directory named dict,
which resides in share, which resides in usr, which resides in the top-level
directory of the system, called .
21. Explain pickling and how import pickle works.
Pickling is so called because it –preserves– data structures. The pickle module
contains the necessary commands. To use it, import pickle and then open the
file in the usual way:
>>> import pickle
>>> f = open(“test.pck”,”w”)
Files , Modules and Packages 5.55

22. What is an exception? Explain with few examples.


Whenever a runtime error occurs, it creates an exception. Usually,the program
stops and Python prints an error message.
Forexample,
dividing by zero creates an exception:
>>> print 55/0 ZeroDivision
Error: integer division or modulo So does accessing a nonexistent list item:
>>> a = []
>>> print a[5]
IndexError: list index out of range
Or accessing a key that isn‘t in the dictionary:
>>> b = {}
>>> print b[‘what‘] KeyError:
what
23. List some few common Exception types and explain when they occur.
 ArithmeticError - Base class for all errors that occur for numeric
calculations.
 OverflowError - Raised when a calculation exceeds maximum limit for
a numeric type.
 ZeroDivisionError - Raised when division or modulo by zero take so
place.
 ImportError - Raised when an import statement fails.
 IndexError - Raised when an index is not found in a sequence.
 RuntimeError - Raised when a generated error does not fall into any
category.
24. Write a simple program which illustrates Handling Exceptions.
w x=int(input(–Please
enter a number:‖)) break
except ValueError:
print(–Oops!
That was no valid number.
Try again…‖)
5. 56 Problem Solving and Python Programming

25. What are packages in Python?


A package is a collection of Python modules. Packages allow us to structure a
collection of modules. Having a directory of modules allows us to have modules
contained within other modules. This allows us to use qualified module names,
clarifying the organization of our software.
26. Explain what is meant by namespaces and scoping.
Variables are names or identifiers that map to objects. A namespace is a
dictionary of variable names/keys and their corresponding object values.
A python statement can access variables in a local namespace and global
namespace. If the local and global variables have the same name, the local
variable shadows the globalvariable. Each function has its own local namespace.

5. Questions
Review 10
1. Answer the following questions.
a. Write a small code to illustrate try and except statements in Python.
(4 marks)
b. What are packages? Give an example of package creation in Python.
(4 marks)
c. Compare and contrast Extending and Embedding Python. (4 marks)
d. Write an algorithm to check whether a student is pass or fail, the total
marks of student being the input. (4 marks)
2. Answer the following questions.
a. Write a program to enter a number in Python and print its octal and
hexadecimal equivalent. (6 marks)
b. Demonstrate the use of Exception Handling in Python.(10 marks)
3. Answer the following questions.
a. What are modules in Python? Explain. (4 marks)
b. Explain in details about namespaces and scoping. (8 marks)
c. Explain about the import statement in modules. (4 marks)
4. Answer the following questions.
a. Explain about the different types of Exceptions in Python. ( 6 marks)
b. Describe about Handling Exceptions in detail with examples. (10 marks)
5. Explain in detail about Python Files, its types, functions and operations
that can be performed on files with examples. (16 marks)

You might also like