Professional Documents
Culture Documents
PROGRAMMING
UNIT 5 - FILES, MODULES, PACKAGES
SYLLABUS
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.
Part-A
Q. Q&A
No.
1. Point out different modes of file opening.
Python File I/O: Read and Write Files in Python
Mode Description
'r' Open a file for reading. (default)
Open file for writing. Creates a new file if it does not exist or truncates
'w'
the file if it exists.
Open a file for exclusive creation. If the file already exists, the
'x' operation
fails.
Open for appending at the end of the file without truncating it. Creates
'a'
a new file if it does not exist.
't' Open in text mode. (default)
'b' Open in binary mode.
'+' Open a Õle for updating (reading and writing)
f = open("test.txt") # equivalent to 'r' or 'rt'
f = open("test.txt",'w') # write in text mode
f = open("img.bmp",'r+b') # read and write in binary mod
1
#Syntax for renaming a file
import os
Syntax
os.remove(file_name)
Example
# Following is the example to delete an existing file test2.txt:
#!/usr/bin/python
import os
os.remove(“text2.txt”)
What is an Exception?
Exceptions are convenient in many ways for handling errors and special conditions
in a program. When you think that you have a code which can produce an error then
you can use exception handling.
2
Exception Cause of Error
3
Raised by parser when syntax error is
SyntaxError encountered.
However, sometimes you may need to create custom exceptions that serves your purpose.
4
User-defined exceptions
Though Python has many built-in exception covering a lot of error scenarios but sometimes you as a user
would want to create your own exception for a specific scenario in order to make error messages more
relevant to the context. Such exceptions are called user-defined exceptions or custom exceptions.
User-defined exception Python example
Suppose you have a Python function that take age as a parameter and tells whether a person is eligible to vote
or not. Voting age is 18 or more.
If person is not eligible to vote you want to raise an exception using raise statement, for this scenario you want
to write a custom exception named “InvalidAgeError”.
# Custom exception
class InvalidAgeError(Exception):
def __init__(self, arg):
self.msg = arg
def vote_eligibility(age):
if age < 18:
raise InvalidAgeError("Person not eligible to vote, age is " + str(age))
else:
print('Person can vote, age is', age)
try:
vote_eligibility(22)
vote_eligibility(14)
except InvalidAgeError as error:
print(error)
Output
10. Write a program to write a data in a file for both write and append modes.
f = open("demofile1.txt", "w")
f.write("I am writing to a new file")
f.close()
OUTPUT
“I am writing to a file”
5
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
OUTPUT
Hello! Welcome to demofile2.txt
This file is for testing purposes.
Good Luck!Now the file has more content!
11. How to import statements?
Modules are Python .py files that consist of Python code. Any Python file can be referenced as a
module. A Python file called hello.py has the module name of hello that can be imported into other
Python files or used on the Python command line interpreter.
Modules can define functions, classes, and variables that you can reference in other Python .py files
or via the Python command line interpreter.
In Python, modules are accessed by using the import statement. When you do this, you execute the
code of the module, keeping the scopes of the definitions so that your current file(s) can make use of
these.
When Python imports a module called hello for example, the interpreter will first search for a built-in
module called hello. If a built-in module is not found, the Python interpreter will then search for a file
named hello.py in a list of directories that it receives from the sys.path variable.
Importing Modules
To make use of the functions in a module, you’ll need to import the module with an import statement.
An import statement is made up of the import keyword along with the name of the module.
In a Python file, this will be declared at the top of the code, under any shebang lines or general
comments.
So, in the Python program file my_rand_int.py we would import the random module to generate
random numbers in this manner:
my_rand_int.py
import random
6
What is a Namespace in Python?
In Python, you can imagine a namespace as a mapping of every name, you have defined, to
corresponding objects.
Different namespaces can co-exist at a given time but are completely isolated.
A namespace containing all the built-in names is created when we start the Python interpreter and
exists as long we don't exit.
This is the reason that built-in functions like id(), print() etc. are always available to us from any part
of the program. Each module creates its own global namespace.
These different namespaces are isolated. Hence, the same name that may exist in different modules
do not collide.
Modules can have various functions and classes. A local namespace is created when a function is
called, which has all the names defined in it. Similar, is the case with class. Following diagram may
help to clarify this concept.
Although there are various unique namespaces defined, we may not be able to access all of them
from every part of the program. The concept of scope comes into play.
Scope is the portion of the program from where a namespace can be accessed directly without any
prefix.
7
At any given moment, there are at least three nested scopes.
When a reference is made inside a function, the name is searched in the local namespace, then in the
global namespace and finally in the built-in namespace.
def outer_function():
a = 20
def inner_function():
a = 30
print('a =',a)
inner_function()
print('a =',a)
a = 10
outer_function()
print('a =',a)
OUTPUT
a = 30
a = 20
a = 10
# Global scope
s = "I am Global"
f()
print s
OUTPUT
I am Local
I am Global
8
directory that just happens to contain a bunch of Python scripts.
>>> date.today()
datetime.date(2017, 9, 1)
Example
filedata = open(file.txt,"r",0)
or
filedata = open(file.txt,"r",1)
or
filedata = open(file.txt,"r",2)
f = open("demofile.txt", "r")
print(f.isatty())
OUTPUT
False
9
18. Create a Python script to display the current date and time.
OUTPUT
2019-12-10 21:02:30 + 5 : 30
19. Analyze the object as return values.
The return statement makes a python function to exit and hand back a value to its caller. The objective
of functions in general is to take in inputs and return something. A return statement, once executed,
immediately halts execution of a function, even if it is not the last statement in the function.
Functions that return values are sometimes called fruitful functions.
def sum(a,b):
return a+b
sum(5,16)
Output
21
Everything in python, almost everything is an object. Lists, dictionaries, tuples are also python objects.
The code below shows a python function that returns a python object; a dictionary
# This function returns a dictionary
def foo():
d = dict();
d['str'] = "Tutorialspoint"
10
d['x'] = 50
return d
print foo()
Output
{'x': 50, 'str': 'Tutorialspoint'}
Importing Modules
Python module : every file, which has the file extension .py and consists of proper Python code, can be seen or is a
module. There is no special syntax required to make such a file a module. A module can contain arbitrary objects, for
example files, classes or attributes. All those objects can be accessed after an import. There are different ways to import a
modules. We demonstrate this with the math module:
import math
The module math provides mathematical constants and functions, e.g. π (math.pi), the sine function (math.sin()) and the
cosine function (math.cos()). Every attribute or function can only be accessed by putting "math." in front of the name:
>>> math.pi
3.141592653589793
>>> math.sin(math.pi/2)
1.0
>>> math.cos(math.pi/2)
6.123031769111886e-17
>>> math.cos(math.pi)
-1.0
PART-B
1. Write a Python program to demonstrate the file I/O operations. The most basic tasks involved in file manipulation
are reading data from files and writing or appending data to files.
In our first example we want to show how to read data from a file. The way of telling Python that we want to read from a
file is to use the open function. The first parameter is the name of the file we want to read and with the second parameter,
assigned to the value "r", we state that we want to read from the file:
11
The "r" is optional. An open() command with just a file name is opened for reading per default. The open() function
returns a file object, which offers attributes and methods.
fobj = open("wordsworth.txt.txt")
After we have finished working with a file, we have to close it again by using the file object method close():
fobj.close()
Now we want to finally open and read a file. The method rstrip() in the following example is used to strip off whitespaces
(newlines included) from the right side of the string "line":
fobj = open("ad_lesbiam.txt")
for line in fobj:
print(line.rstrip())
fobj.close()
OUTPUT
2. Discuss the different modes for opening a file and closing a file.
Python has a built-in function open() to open a file. This function returns a file object, also called a
handle, as it is used to read or modify the file accordingly.
We can specify the mode while opening a file. In mode, we specify whether we want to read 'r',
write 'w' or append 'a' to the file. We also specify if we want to open the file in text mode or binary
mode.
The default is reading in text mode. In this mode, we get strings when reading from the file.
On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-
text files like image or exe files.
Mode Description
12
'r' Open a file for reading. (default)
Open a file for writing. Creates a new file if it does not exist or truncates the file
'w' if it exists.
'x' Open a file for exclusive creation. If the file already exists, the operation fails.
Open for appending at the end of the file without truncating it. Creates a new file
'a' if it does not exist.
When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done using
Python close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to close
the file.
1. f = open("test.txt",encoding = 'utf-8')
2. # perform file operations
3. f.close()
This method is not entirely safe. If an exception occurs when we are performing some operation with
the file, the code exits without closing the file.
13
3. # perform file operations
4. finally:
5. f.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised, causing
program flow to stop.
3. i) Write a program to catch a divide by zero exception. Add a finally block too.
> def divide(x, y):
... try:
... result = x / y
... except ZeroDivisionError:
... print("division by zero!")
... else:
... print("result is", result)
... finally:
... print("executing finally clause")
...
>>> divide(2, 1)
result is 2.0
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in divide
TypeError: unsupported operand type(s) for /: 'str' and 'str'
ii) Write a function to print the hash of any given file in Python.
# Python 3 code to demonstrate
# SHA hash algorithms.
import hashlib
# initializing string
str = "GreekandLatin"
14
print ("\r")
# initializing string
str = "GreekandLatin"
print ("\r")
OUTPUT
The hexadecimal equivalent of SHA256 is :
bed3b89c643693e40b1bb6f8ae65cb75eb5925e03918179e801f79e399980efc
4. i) Describe the use of try block and except block in python with syntax.
What is Exception?
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.
Handling an exception
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
......................
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.
EXAMPLE
15
This example opens a file, writes content in the, file and comes out gracefully because there is no
problem at all −
#!/usr/bin/python3
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 −
Written content in the file successfully
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;
......................
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
Following is an example for a single exception −
#!/usr/bin/python
16
# Call above function here.
temp_convert("xyz");
This produces the following result −
The argument does not contain numbers
invalid literal for int() with base 10: 'xyz'
A file object is created using open function and here is a list of functions which can be called on this
object −
1 file.close()
Close the file. A closed file cannot be read or written any more.
2 file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like objects.
3 file.fileno()
Returns the integer file descriptor that is used by the underlying implementation to request I/O
operations from the operating system.
4 file.isatty()
Returns True if the file is connected to a tty(-like) device, else False.
5 file.next()
Returns the next line from the file each time it is being called.
6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
7 file.readline([size])
Reads one entire line from the file. A trailing newline character is kept in the string.
8 file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. If the optional sizehint
17
argument is present, instead of reading up to EOF, whole lines totalling approximately
sizehint bytes (possibly after rounding up to an internal buffer size) are read.
9 file.seek(offset[, whence])
Sets the file's current position
10 file.tell()
Returns the file's current position
11 file.truncate([size])
Truncates the file's size. If the optional size argument is present, the file is truncated to (at most)
that size.
12 file.write(str)
Writes a string to the file. There is no return value.
13 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any iterable object producing strings,
typically a list of strings.
OS module in Python provides functions for interacting with the operating system. OS comes under
Python’s standard utility modules. This module provides a portable way of using operating system
dependent functionality.
os.rename() method in Python is used to rename a file or directory.
This method renames a source file/ directory to specified destination file/directory.
Parameters:
source: A path-like object representing the file system path. This is the source file path which is to
renamed.
18
# Python program to explain os.rename() method
# importing os module
import os
19
random.randint() which calls the
function to return a random integer, Output
or
random.randrange() which calls the 6
function to return a random element 9
from a specified range. 1
14
The import statement allows you to import one 3
or more modules into your Python program, 22
letting you make use of the definitions 10
constructed in those modules.
1
15
9
Using from … import my_rand_int.py
To refer to items from a module within your from random import randint
program’s namespace, you can use Here, we first call the from keyword,
the from … import statement. When you then random for the module. Next, we use
import modules this way, you can refer to the import keyword and call the specific
the functions by name rather than through function we would like to use.
dot notation
Now, when we implement this function
In this construction, you can specify which within our program, we will no longer write
definitions to reference directly. the function in dot notation
as random.randint() but instead will just
In other programs, you may see write randint():
the import statement take in references to
everything defined within the module by my_rand_int.py
using an asterisk (*) as a wildcard, but this from random import randint
is discouraged by PEP 8.
20
my_math.py
import math as m
Aliasing Modules
It is possible to modify the names of
modules and their functions within Python print(m.pi)
by using the as keyword. print(m.e)
Within the program, we now refer to
You may want to change a name because the pi constant as m.pi rather than math.pi.
you have already used the same name for
something else in your program, another For some modules, it is commonplace to use
module you have imported also uses that aliases. The matplotlib.pyplot module’s
name, or you may want to abbreviate a official documentation calls for use of plt as
longer name that you are using a lot. an alias:
For modules to be available for use, the Python interpreter must be able to locate the module file. Python has a set
of directories in which it looks for module files. This set of directories is called the search path, and is analogous to
the PATH environment variable used by an operating system to locate an executable file.
PYTHONHOME is used to define directories that are part of the Python installation. If this environment
variable is not defined, then a standard directory structure is used. For Windows, the standard location is
based on the directory into which Python is installed. For most Linux environments, Python is installed
under /usr/local, and the libraries can be found there. For Mac OS, the home directory is
under /Library/Frameworks/Python.framework.
PYTHONPATH is used to add directories to the path. This environment variable is formatted like the
OS PATH variable, with a series of filenames separated by :'s (or ;'s for Windows).
21
Script Directory. If you run a Python script, that script's directory is placed first on the search path so that
locally-defined moules will be used instead of built-in modules of the same name.
The site module's locations are also added. (This can be disabled by starting Python with the -S option.)
The site module will use the PYTHONHOME location(s) to create up to four additional directories.
Generally, the most interesting one is the site-packages directory. This directory is a handy place to put
additional modules you've downloaded. Additionally, this directory can contain .PTH files. The site module
reads .PTH files and puts the named directories onto the search path.
The search path is defined by the path variable in the sys module. If we import sys, we can display sys.path. This is
very handy for debugging. When debugging shell scripts, it can help to run 'python -c 'import sys; print sys.path' just
to see parts of the Python environment settings.
Installing a module, then, is a matter of assuring that the module appears on the search path. There are four central
methods for doing this.
Some packages will suggest you create a directory and place the package in that directory. This may be
done by downloading and unzipping a file. It may be done by using Subversion and sychronizing your
subversion copy with the copy on a server. Either way, you will likely only need to create an operating
system link to this directory and place that link in site-packages directory.
Some packages will suggest you download (or use subversion) to create a temporary copy. They will
provide you with a script — typically based on setup.py — which moves files into the correct locations.
This is called the distutils distribution. This will generally copy the module files to the site-
packages directory.
Some packages will rely on setuptools. This is a package from the Python Enterprise Application
Kit that extends distuils to further automates download and installation. This tool, also, works by moving
the working library modules to the site-packages directory.
Extending the search path. Either set the PYTHONPATH environment variable, or put .PTH files in the site-
packages directory.
Windows Environment
In the Windows environment, the Python_Path symbol in the Windows registry is used to locate modules.
9. Identify the various methods used to delete the elements from the dictionary
Python | Ways to remove a key from dictionary
Dictionary is used in manifold practical applications such as day-day programming, web
development and AI/ML programming as well, making it a useful container overall. Hence, knowing
shorthands for achieving different tasks related to dictionary usage always is a plus. This article deals
with one such task of deleting a dictionary key-value pair from a dictionary.
22
Code #1 : Demonstrating key-value pair operation.
deletion using del
Code #2 : Demonstrating key-value pair
deletion using pop()
# Python code to demonstrate
# removal of dict. pair
# using del # Python code to demonstrate
# removal of dict. pair
# Initializing dictionary # using pop()
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
# Initializing dictionary
# Printing dictionary before removal test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" :
print ("The dictionary before performing remove is : " + str(test_dict))
# Printing dictionary before removal
# Using del to remove a dict print ("The dictionary before performing remove is : " + str(test_dict
# removes Mani
del test_dict['Mani'] # Using pop() to remove a dict. pair
# removes Mani
# Printing dictionary after removal removed_value = test_dict.pop('Mani')
print ("The dictionary after remove is : " + str(test_dict))
# Printing dictionary after removal
# Using del to remove a dict print ("The dictionary after remove is : " + str(test_dict))
# raises exception print ("The removed key's value is : " + str(removed_value))
del test_dict['Manjeet']
Output : print ('\r')
The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21}
# Using pop() to remove a dict. pair
The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}
# doesn't raise exception
Exception : # assigns 'No Key found' to removed_value
removed_value = test_dict.pop('Manjeet', 'No Key found')
Traceback (most recent call last):
# Printing
File "/home/44db951e7011423359af4861d475458a.py", dictionary
line 20, in after removal
print ("The dictionary after remove is : " + str(test_dict))
del test_dict['Manjeet'] print ("The removed key's value is : " + str(removed_value))
Output :
KeyError: 'Manjeet'
The dictionary before performing remove is :
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21,
'Haritha': 21}
The dictionary after remove is : {'Arushi': 22,
'Anuradha': 21, 'Haritha': 21}
The removed key's value is : 21
23
has drawback of not being an inplace dict. technique. Actually a new dict if created except for the
key we don’t wish to include.
# Initializing dictionary
test_dict = {"Arushi" : 22, "Anuradha" : 21, "Mani" : 21, "Haritha" : 21}
24
execute all the code that exists after the that.
5. EOFError: It occurs when the end of the
file is reached, and yet operations are being
performed.
Example Example
If the python program contains suspicious code that The syntax to use the else statement with the try-
may throw the exception, we must place that code in except statement is given below.
the try block. The try block must be followed with
the except statement which contains a block of code
1.
that will be executed if there is some exception in the try:
try block. 2. #block of code
3.
Syntax 4. except Exception1:
5. #block of code
1. try: 6.
2. #block of code 7. else:
3. 8. #this code executes if no except block is e
4. except Exception1: xecuted
5. #block of code
25
6.
7. except Exception2:
8. #block of code
9.
10. #other code
11. Write a program to find the one’s complement of binary number using file.
# Python3 program to print 1's and 2's
# complement of a binary number
n = len(bin)
ones = ""
twos = ""
if (ones[i] == '1'):
twos[i] = '0'
else:
twos[i] = '1'
break
26
twos.insert(0, '1')
# Driver Code
if __name__ == '__main__':
bin = "111100"
printOneAndTwosComplement(bin.strip(""))
OUTPUT
1's complement: 000011
2's complement: 000100
# Function to print
# Diamond shape
def Pyramid(rows):
n=0
for i in range(1, rows + 1):
# loop to print spaces
for j in range (1, (rows - i) + 1):
print(end = " ")
# line break
print()
# Driver Code
# number of rows input
rows = 10
Pyramid(rows)
13. Write a program to find the number of instances of different digits in a given number
# Python program to find the frequency of each element of an array
27
for i in range(0, n):
count = 1
for j in range(i+1, n):
if(arr[i] == arr[j]):
count = count + 1
freq[j] = 0
if(freq[i] != 0):
freq[i] = count
OUTPUT
Enter a number : 43829
Frequency of all elements of array :
4 occurs -1 times
3 occurs -1 times
8 occurs -1 times
2 occurs -1 times
9 occurs 1 times
14. Describe in detail printing to the screen.
Screen output
Text output is one of the basics in Python programming. Not all Programs have graphical user interfaces, text
screens often suffice.
You can output to the terminal with print function. This function displays text on your screen, it won’t print.
The terminal is a very simple interface for Python programs. While not as shiny as a GUI or web app, it’s
good enough to cover the basics in.
Print function
print("Hello World")
Hello World
28
Print newline
The program above prints everything on a single line. At some point you’ll want to write multiple lines.
OUTPUT
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in
representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
Print variables
To print variables:
x=3
print(x)
OUTPUT
x=2
y=3
print("x = {}, y = {}".format(x,y))
OUTPUT:
x = 2, y = 3
29
30