Unit V
Unit V
UNIT V
FILES, MODULES, PACKAGES
Files and exception: text files, reading and writing files, format operator; command
line arguments, errors and exceptions, handling exceptions, modules, packages;
Illustrative programs: word count, copy file.
5. FILES
5.1 PRINTING TO THE SCREEN
The simplest way to produce output is using the print statement where you can
pass zero or more expressions separated by commas. This function converts the
expressions you pass into a string and writes the result to standard output as
follows
#!/usr/bin/python
raw_input
input
5.1.2 THE RAW_INPUT FUNCTION
The raw_input([prompt]) function reads one line from standard input and returns
it as a string (removing the trailing newline).
#!/usr/bin/python
#!/usr/bin/python
The open Function
Before you can read or write a file, you have to open it using Python's built-
in open() function. This function creates a file object, which would be utilized to
call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details:
values is given below in the table. This is optional parameter and the default
file access mode is read (r).
Mode Description
s
Attribute Description
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
print "Closed or not : ", fo.closed
print "Opening mode : ", fo.mode
print "Softspace flag : ", fo.softspace
This produces the following result −
Python automatically closes a file when the reference object of a file is reassigned
to another file. It is a good practice to use the close() method to close a file.
147
Syntax
fileObject.close();
Example
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
The write() Method
The write() method writes any string to an open file. It is important to note that
Python strings can have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string
−
Syntax
fileObject.write(string);
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python
148
# Open a file
fo = open("foo.txt", "wb")
fo.write( "Python is a great language.\nYeah its great!!\n");
Syntax
fileObject.read([count]);
Here, passed parameter is the number of bytes to be read from the opened file.
This method starts reading from the beginning of the file and if count is missing,
then it tries to read as much as possible, maybe until the end of file.
Example
Let's take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
149
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.
Example
Let us take a file foo.txt, which we created above.
#!/usr/bin/python
# Open a file
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
To use this module you need to import it first and then you can call any related
functions.
Syntax
os.rename(current_file_name, new_file_name)
Example
Following is the example to rename an existing file test1.txt:
#!/usr/bin/python
import os
Syntax
os.remove(file_name)
151
Example
Following is the example to delete an existing file test2.txt −
#!/usr/bin/python
import os
The mkdir() Method
You can use the mkdir() method of the os module to create directories in the
current directory. You need to supply an argument to this method which contains
the name of the directory to be created.
Syntax
os.mkdir("newdir")
Example
Following is the example to create a directory test in the current directory −
#!/usr/bin/python
import os
Syntax
152
os.chdir("newdir")
Example
Following is the example to go into "/home/newdir" directory −
#!/usr/bin/python
import os
Syntax
os.getcwd()
Example
Following is the example to give current directory −
#!/usr/bin/python
import os
Syntax:
os.rmdir('dirname')
Example
153
#!/usr/bin/python
import os
5.2 EXCEPTION
Python provides two very important features to handle any unexpected error in
your Python programs and to add debugging capabilities in them −
EXCEPTION DESCRIPTION
NAME
any object.
specified properly.
Assertions are carried out by the assert statement, the newest keyword to Python,
introduced in version 1.5.
157
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.
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 −
#!/usr/bin/python
def KelvinToFahrenheit(Temperature):
assert (Temperature >= 0),"Colder than absolute zero!"
return ((Temperature-273)*1.8)+32
print KelvinToFahrenheit(273)
print int(KelvinToFahrenheit(505.78))
print KelvinToFahrenheit(-5)
When the above code is executed, it produces the following result −
32.0
451
Traceback (most recent call last):
File "test.py", line 9, in
print KelvinToFahrenheit(-5)
File "test.py", line 4, in KelvinToFahrenheit
assert (Temperature >= 0),"Colder than absolute zero!"
158
When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates and quits.
Syntax
Here is simple syntax of try....except...else blocks −
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
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.
159
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, writes content in the, file and comes out gracefully
because there is no problem at all −
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print "Error: can\'t find file or read data"
else:
print "Written content in the file successfully"
fh.close()
This produces the following result −
#!/usr/bin/python
try:
fh = open("testfile", "r")
fh.write("This is my test file for exception handling!!")
except IOError:
160
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.
try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
161
else:
If there is no exception then execute this block.
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
#!/usr/bin/python
try:
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
finally:
print "Error: can\'t find file or read data"
If you do not have permission to open the file in writing mode, then this will
produce the following result:
#!/usr/bin/python
162
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"
When an exception is thrown in the try block, the execution immediately passes to
the finally block. After all the statements in the finally block are executed, the
exception is raised again and is handled in the exceptstatements if present in the
next higher layer of the try-except statement.
try:
You do your operations here;
......................
except ExceptionType, 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
163
#!/usr/bin/python
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 −
164
In the try block, the user-defined exception is raised and caught in the except
block. The variable e is used to create an instance of the class Networkerror.
class Networkerror(RuntimeError):
def __init__(self, arg):
self.args = arg
So once you defined above class, you can raise the exception as follows −
try:
raise Networkerror("Bad hostname")
except Networkerror,e:
print e.args
165
Example
Consider the following script test.py −
#!/usr/bin/python
import sys
getopt.getopt method
This method parses command line options and parameter list. Following is simple
syntax for this method −
The argument to the exception is a string indicating the cause of the error. The
attributes msg and opt give the error message and related option
Example
Consider we want to pass two file names through command line and we also want
to give an option to check the usage of the script. Usage of the script is as follows
−
#!/usr/bin/python
167
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print 'Input file is "', inputfile
print 'Output file is "', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
Now, run above script as follows −
$ test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ test.py -i BMP -o
usage: test.py -i <inputfile> -o <outputfile>
168
$ test.py -i inputfile
Input file is " inputfile
Example
The Python code for a module named aname normally resides in a file
named aname.py. Here's an example of a simple module, support.py
#!/usr/bin/python
Hello : Zara
A module is loaded only once, regardless of the number of times it is imported.
This prevents the module execution from happening over and over again if
multiple imports occur.
The from...import Statement
Python's from statement lets you import specific attributes from a module into the
current namespace. The from...import has the following syntax −
The from...import * Statement:
It is also possible to import all names from a module into the current namespace
by using the following import statement −
If the module isn't found, Python then searches each directory in the shell
variable PYTHONPATH.
If all else fails, Python checks the default path. On UNIX, this default path
is normally /usr/local/lib/python/.
The PYTHONPATH Variable:
The PYTHONPATH is an environment variable, consisting of a list of directories.
The syntax of PYTHONPATH is the same as that of the shell variable PATH.
set PYTHONPATH=c:\python20\lib;
And here is a typical PYTHONPATH from a UNIX system:
set PYTHONPATH=/usr/local/lib/python
5.4.2 NAMESPACES AND SCOPING
Variables are names (identifiers) that map to objects. A namespace is a dictionary
of variable names (keys) and their corresponding objects (values).
Each function has its own local namespace. Class methods follow the same
scoping rule as ordinary functions.
#!/usr/bin/python
Money = 2000
def AddMoney():
# Uncomment the following line to fix the code:
# global Money
Money = Money + 1
print Money
AddMoney()
print Money
The dir( ) Function
The dir() built-in function returns a sorted list of strings containing the names
defined by a module.
The list contains the names of all the modules, variables and functions that are
defined in a module. Following is a simple example −
#!/usr/bin/python
content = dir(math)
print content
When the above code is executed, it produces the following result −
172
The globals() and locals() Functions −
The globals() and locals() functions can be used to return the names in the global
and local namespaces depending on the location from where they are called.
If locals() is called from within a function, it will return all the names that can be
accessed locally from that function.
If globals() is called from within a function, it will return all the names that can be
accessed globally from that function.
The return type of both these functions is dictionary. Therefore, names can be
extracted using the keys() function.
The reload() Function
When the module is imported into a script, the code in the top-level portion of a
module is executed only once.
Therefore, if you want to reexecute the top-level code in a module, you can use
the reload() function. The reload() function imports a previously imported module
again. The syntax of the reload() function is this −
reload(module_name)
Here, module_name is the name of the module you want to reload and not the
string containing the module name. For example, to reload hello module, do the
following −
reload(hello)
5.4.3 PACKAGES IN PYTHON
173
#!/usr/bin/python
def Pots():
print "I'm Pots Phone"
Similar way, we have another two files having different functions with the same
name as above −
Phone/__init__.py
To make all of your functions available when you've imported Phone, you need to
put explicit import statements in __init__.py as follows −
#!/usr/bin/python
Phone.Pots()
174
Phone.Isdn()
Phone.G3()
When the above code is executed, it produces the following result −