unit V
unit V
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.
FILES
File is a named location on disk to store related information. It is used to permanently store
data in a non-volatile memory (e.g. hard disk).
Since, random access memory (RAM) is volatile which loses its data when computer is
turned off, we use files for future use of the data.
When we want to read from or write to a file we need to open it first. When we are done, it
needs to be closed, so that resources that are tied with the file are freed. Hence, in Python, a file
operation takes place in the following order.
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening 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.
>>> f = open("test.txt") # open file in current directory
>>> f = open("C:/Python33/README.txt") # specifying full path
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.
Closing a File
When we are done with operations to the file, we need to properly close it.
Closing a file will free up the resources that were tied with the file and is done using the
close() method.
Python has a garbage collector to clean up unreferenced objects but, we must not rely on it to
close the file.
file_object = open("test.txt")# perform file operations
file_object.close()
This method is not entirely safe. If an exception occurs when we are performing someoperation
with the file, the code exits without closing the file. A safer way is to use a try...finally block.
try:
file_object = open("test.txt")# perform file operations
finally: # error may or may not happened in try block this will be executed
file_object.close()
This way, we are guaranteed that the file is properly closed even if an exception is raised,
causing program flow to stop.
The best way to do this is using the with statement. This ensures that the file is closed whenthe
block inside with is exited.
We don't need to explicitly call the close() method. It is done internally. with open("test.txt") as
f:
# perform file operations
A text file is a sequence of characters stored on a permanent medium like a hard drive, flash
memory, or CD-ROM.
These two functions are considered as most basic of all input/output functions in file handling.
The write() function writes characters to a disk file that was previously opened for writing,
through the use of the function open(). Similarly read() function is used to read characters from
file_object.read(no_of_bytes_to_be_read)
a file opened in read mode by open().The general format for read() method is:
Here the argument no_of_bytes_to_be_read the numerical value indicates the no of characters
to be read at a time, it is optional, if not mentioned the entire content of file has been read
file_object.read()
To write a file, you have to open it with mode 'w' as a second parameter:
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>
If the file already exists, opening it in write mode clears out the old data and starts fresh, so be
careful! If the file doesn’t exist, a new one is created.
The write method puts data into the file.
>>> line1 = "This here's the wattle,\n"
>>> fout.write(line1)
Again, the file object keeps track of where it is, so if you call write again, it adds the new datato
the end.
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
When you are done writing, you have to close the file.
>>> fout.close()
out=open("abc.dat","w")
str= input("Enter string : ")
out.write(str)
out.close() out=open("abc.dat","r") str=out.read()
print("File contains") print(str)
out.close()
Output
Enter string : Welcome to Python file handling File contains
Welcome to Python file handling
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:
>>> x = 52
>>> fout.write(str(x))
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 the second operand should be formatted asan
integer (d stands for “decimal”):
>>> camels = 42
>>> '%d' % camels'42'
The result is the string '42', which is not to be confused with the integer value 42.
A format sequence can appear anywhere in the string, so you can embed a value in asentence:
>>> camels = 42
>>> 'I have spotted %d camels.' %camels
‘I have spotted 42 camels.'
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.
The following example uses '%d' to format an integer, '%g' to format a floating-point number
and '%s' to format a string:
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels') 'In 3 years I have spotted 0.1
camels.'
The number of elements in the tuple has to match the number of format sequences inthe string.
Also, the types of the elements have to match the format sequences:
Files are organized into directories (also called “folders”). Every running programhas 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
>>> cwd = os.getcwd()
>>> print cwd
/home/dinsdale
cwd stands for “current working directory.” The result in this example is /home/dinsdale, which
is the home directory of a user named dinsdale.
A string like cwd that identifies a file is called a path. A relative path starts from the current
directory; an absolute path starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative to the currentdirectory.
To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt') '/home/dinsdale/memo.txt'
os.path.exists checks whether a file or directory exists:
>>> os.path.exists('memo.txt') True
>>> os.listdir(cwd)
['music', 'photos', 'memo.txt']
To demonstrate these functions, the following example “walks” through a directory, prints the
names of all the files, and calls itself recursively on all the directories.
def walk(dirname):
for name in os.listdir(dirname):
path = os.path.join(dirname, name)
if os.path.isfile(path):
print( path)
else:
walk(path)
os.path.join takes a directory and a file name and joins them into a complete path.
Normally in a program inputs are given during execution of the program. Situation in which we
have to pass the input to the program at the time of execution get started can be possible
through command line arguments. Inputs can be directly sent as an argument of the program.
When the program is running under command prompt then inputs can be passed directly in the
command and can be fetched using "sys" module.
Example program:
import sys
noargs=len(sys.argv)
print ("Number of arguments :%d" %noargs) arguments= str(sys.argv)
print ("Arguments are : %s" %arguments)
Output
EXCEPTION
Example,
>>> if a < 3
File "<interactive input>", line 1if a < 3
^
Common occurring syntax errors are
Example:
>>> 1 / 0
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>ZeroDivisionError: division by zero
Handling Exceptions:
Definition
– An exception is an event, which occurs during theexecution of the program that disrupts the
normal flow of the program.
When the program raises an exception, then python must handlethe exception otherwise it
terminates and quits
The handling mechanism is done by try, except and else blocks
try:
write the suspicious code hereexcept exception1:
If exception1 occurs then this block will be executedexcept exception2:
If exception2 occurs then this block will be executed
.
..
else:
It is up to us, what operations we perform once we have caught the exception. Here is a
simple example.
# import module sys to get the type of exception
import sys
randomList = ['a', 0, 2]
for entry in randomList:
try:
print("The entry is", entry) r = 1/int(entry)
except:
print("Oops!",sys.exc_info()[0],"occured.")print("Next entry.")
else:
print("The reciprocal of",entry,"is",r)
finally:
print(“I will be always executed”)
print()
Output
The entry is a
Oops! <class 'ValueError'> occured. Next entry.
I will be always executed
The entry is 0
Oops! <class 'ZeroDivisionError' > occured. Next entry.
I will be always executed
The entry is 2
The reciprocal of 2 is 0.5
I will be always executed
In this program, we loop until the user enters an integer that has a valid reciprocal. Theportion
that can cause exception is placed inside try block. If no exception occurs, except block is
skipped else block is called for normal execution flow.
Here, we print the name of the exception using exc_info() function inside sys module and ask
the user to try again. We can see that the values 'a' causes ValueError and '0' causes
ZeroDivisionError.
MODULES
In Python, module is a file that contains python programming code consist of definitions of
functions, variables and classes. The module name is the same as the file name. We have used
some scientific functions that present in math module and it is a built in module in Python. The
main advantage of using module is it allows us to make our programs more robust and powerful.
We can have our own module and in our example program we created a module by name
“compute_operations.py”. The module contains two functions definition namely fact() and
summation(). The coding is as follows.
def fact(n):
f=1
for i in range(1,n+1):
f=f*i
return (f)
def summation(n):
s=0
for i in range(1,s+1):
s=s+i
return (s)
after that we can create a python program moduletest.py to use the services provided by the
above developed module named compute_operations. This can be achieved by importing that
module to our program
# Module test example - moduletest.py
import compute_operations
n=int(input("Enter number to find factorial :"))
print ("Factorial of a given number is %d"% compute_operations.fact(n))
m=int(input("Enter number to find summation :"))
print("The summation of number is %d"% compute_operations.summation(m))
Output
Enter number to find factorial :5
Factorial of a given number is 120
Enter number to find summation 7
The summation of number is 28
PACKAGE
A package is a collection of modules. A Python package can have sub-packages and modules.
A directory (folder) must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that
package in this file.
Here is an example. Suppose we are developing a game, one possible organization of packages
and modules could be as shown in the figure below.
Now if this module contains a function named select_difficulty(), we must use the full name to
reference it.
Game.Level.start.select_difficulty()
If this construct seems lengthy, we can import the module without the package prefix as follows.
from Game.Level import start
Example Program:
def add(a,b):
return (a+b)
Step 4: Now write another python program named find_sum.py and keep this one in python
default location in order to utilize the services provided by the package defined in that location.
ILLUSTRATION PROGRAM
import sys
fname=sys.argv[1]
n=0
with open(fname,'r') as f:
for line in f:
words=line.split()
n+=len(words)
print("Number of words:",n)
Output:
C:\Users\admin\AppData\Local\Programs\Python\Python37-32>python command_demo.py
word_freq.py
Number of words: 28
2) Copy file:
f1=open(“sourcefile.txt”,”r”)
f2=open(“destinationfile.txt”,”w”)
for line in f1:
f2.write(“\n”+line)
f1.close( )
f2.close( )
print(“Content of Source file:”)
f1=open(“sourcefile.txt”,”r”)
print(f1.read( ))
f1.close()
print(“Content of Copied file:”)
f2=open(“destinationfile.txt”,”r”)
print(f2.read( ))
f2.close()
Output: