Unit - 5 PSP
Unit - 5 PSP
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.
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.
A collection of data or information that has a name,
called the filename.
Almost all information stored in a computer must be
in a file.
TYPES OF FILES
Data files
Text files
Program files
Directory files
File Operations
In Python, a file operation takes place in the following
order.
file_object = open(“filename”,
“mode”)
binary mode
2. Reading and writing files
a) write()
b) read()
write() Method
This 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)
sam1.txt
Example I will try my best.
God is always with me!!
# Open a file
f= open(“sam1.txt”, “wb”)
f.close()
read() Method
This method reads a string from an open file. It is
important to note that Python strings can have
binary data apart from text data.
Count 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. Syntax
fileObject.read((count))
sample.txt
Example-1 I will try my best.
God is always with me!!
# Open a file
f= open(“sam1.txt”, “r+”)
str=f.read(10);
print(str)
f.close()
Output :
I will try
sample.txt
readLine() functionI will try my best.
God is always with me!!
# Open a file
f= open(“sam1.txt”, “r+”)
print(f.readLine())
f.close()
Output :
file_object .close()
sample.txt
Example I will try my best.
God is always with me!!
# Open a file
f= open(“sam1.txt”, “r+”)
str=f.read(10);
print(str)
f.close()
Output :
I will try
Looping over a file object
The user want to read – or return – all the lines from a
file in a more memory efficient, and fast manner, user
can use the loop over method. The advantage to using
this method is that the related code is both simple and
Welcome to
Example
easy to: read. Akshaya college
By
file = open(“samtext.txt”, 2017 Batch
“r”)
for line in file: Output
print line Welcome to
Akshaya college
By
2017 Batch
With Statement
The user can also work with file objects using the with
statement. It is designed to provide much cleaner
syntax and exceptions handling when you are working
with code.
Advantages
If any files opened will be closed automatically after
you are done. This leaves less to worry about during
Welcome to
cleanup. Akshaya college
Example : By
2017 Batch
with open(“testfile.txt”) as
file: Output
WELCOME TO
data = file.read() AKSHAYA COLLEGE
print(data.upper()) BY
2017 BATCH
Splitting Lines in a Text File
This function that allows you to split the lines taken from a
text file. What this is designed to do, is split the string
contained in variable data whenever the interpreter
encounters a space character.
Example : Welcome to Akshaya college
By 2017 Batch
with open(“hello.text”, “r”)
as f:
data = f.readlines() Output
for line in data: [“Welcome”, “to”,
words = line.split() “Akshaya”, “By”, “2017”,
“Batch”]
print words
The file Object Attributes
Attribute Description
os.rename(current_file_name, new_file_name)
Example
import os
# Rename a file from test1.txt to test2.txt
os.rename( “test1.txt”, “test2.txt” )
Deleting a File
remove() Method
This method is used to delete files by
supplying the name of the file to be deleted as the
argument.
Syntax
os.remove(file_name)
Example
import os
# Rename a file from test1.txt to test2.txt
os.remove( “test1.txt”)
Command-line options and
arguments
Python provides a getopt module that helps you
parse command-line options and arguments.
a) Syntax errors
b) Runtime errors
c) Logical errors
HANDLING EXCEPTIONS
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.
Python provides two very important features to handle
any unexpected error in the Python programs and to
add debugging capabilities in them.
i) Exception Handling
ii) Assertions
Standard Exceptions
Assertions
An assertion is a sanity-check that you can turn on or
turn off when you are done with your testing of the
program.
Syntax :
Output
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!”
AssertionError: Colder than absolute zero!
Logic – HandlingExceptions
Syntax :
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.
mportant points about syntax:
fh = open(“testfile”, “r”)
except IOError:
else:
Syntax:
from modname import name1[, name2[, ...
nameN]]
PACKAGES
A package is a hierarchical file directory structure that
defines a single Python application environment that
consists of modules and subpackages and sub-
subpackages, and so on.
Consider a file Pots.py available in Phone directory. This
file has following line of source code:
def Pots():
print “I’m Pots Phone”
Similar way, we have another two files having different
functions with the same name as above:
Phone/Isdn.py file having function Isdn()
Phone/G3.py file having function G3()
Now, create one more file __init__.py in Phone directory:
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:
from Pots import Pots
from Isdn import Isdn
from G3 import G3
After you add these lines to __init__.py, you have all of these classes available
when you import the Phone package.
# Now import your Phone Package.Output
import Phone
I’m Pots Phone
Phone.Pots()
I’m 3G Phone
Phone.Isdn()
I’m ISDN Phone
Phone.G3()
ILLUSTRATIVE PROGRAMS
Program 1: Word Count
# Word Count
file=open(“C:/python27/python operators.txt”,”r+”)
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
print k, v
Program 2: Copy Files
# Copy Files
from shutil import copyfile
while True:
print(“Enter ‘x’ for exit.”)
sourcefile = input(“Enter source file name: “)
destinationfile = input(“Enter destination file name: “)
if sourcefile == ‘x’:
break
else:
copyfile(sourcefile, destinationfile)
print(“File copied successfully!”)