0% found this document useful (0 votes)
86 views

PSPP Unit 5 Notes

The document discusses files, modules, packages and exceptions in Python. It covers reading, writing and manipulating text files, using format operators and command line arguments. Example programs demonstrate opening, closing, reading and writing to files. Exceptions and error handling are also covered.

Uploaded by

Yokesh Kumar B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views

PSPP Unit 5 Notes

The document discusses files, modules, packages and exceptions in Python. It covers reading, writing and manipulating text files, using format operators and command line arguments. Example programs demonstrate opening, closing, reading and writing to files. Exceptions and error handling are also covered.

Uploaded by

Yokesh Kumar B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

`

UNIT V : FILES, MODULES AND PACKAGES


Files and exceptions: text files, reading and writing files, format operator;
command line arguments, errors and exceptions, handling exceptions, modules,
packages; Illustrative programs: word count, copy file, Voter’s age validation,
Marks range validation (0-100).

5.1 FILES AND EXCEPTIONS


5.1.1 FILES
❖ File is a named location on disk to store related information. It is used to store data
permanently in a memory (e.g. hard disk).
❖ File Types: 1) Text file 2) binary file
Text File Binary file
Text file is a sequence of characters that A binary files store the data in the binary
can be sequentially processed by a format (i.e. 0 s and 1 s ). It contains any
Computer in forward direction. type of data ( PDF, images , Word doc,
Spreadsheet, Zip files,etc)
Each line is terminated with a special No termination character for binary file
character, called the EOL [End Of
Line character]
Operations on Files
In Python, a file operation takes place in the following order,
1. Open a file
2. Write a file
3. Read a file
4. Close a file

Open a file
Syntax: Example:
file_object=open(“ file_name.txt” , mode ) f=open( “sample.txt” , ‘w ‘)
1. Write a file
Syntax: Example:
file_object.write(string) f.write( ‘hello’ )

2. Read a file
Syntax
file_object.read(string) f.read( )
3. Close a file
Syntax
file_object.close() f.close()

Modes description
r read only mode
w write only
a appending mode

1
`
r+ read and write mode
w+ write and read mode

Differentiate write and append mode


write mode append mode
It is used to write a string into a file. It is used to append (add) a string into a file.
If file does not exist it creates a new file. If file does not exist it creates a new file.
If file is exist in the specified name, the It will add the string at the end of the old file.
existing content will be overwritten by the
given string.

File operations and methods:


S.No Syntax Example Description
1 fileobject.write(string) f.write("hello") Writing a string into a file.
f.writelines (“1st line \n Writes a sequence of strings to
2 fileobject.writelines(sequence) second line” ) the file.
f.read( ) #read entire file To read the content of a file.
3 fileobject.read(size) f.read(4) #read the
first 4 char
4 fileobject.readline( ) f.readline( ) Reads one line at a time.
5 fileobject.readlines( ) f.readlines( ) Reads the entire file and returns
a list of lines.
f.seek(offset,[whence]) Move the file pointer to the
f.seek(0) appropriate position. seek(0)
[whence value is optional.] sets the file pointer to the
starting of the file.
[whence =0 - from beginning] f.seek(3,0) Move three characters from the
6 beginning.
[whence =1 - from current Move three characters ahead
position] f.seek(3,1) from the current position.
[whence =2 - from last f.seek(-1,2) Move to the first character from
position] end of the file
7 fileobject.tell( ) f.tell( ) Get the current file pointer
position.
8 fileobject.flush( ) f.flush( ) To flush the data before closing
any file.
9 fileobject.close( ) f.close( ) Close an open file.
10 fileobject.name f.name Return the name of the file.
11 fileobject.mode f.mode Return the Mode of file.
12 os.rename(old import os Renames the file or directory.
name,new name ) os.rename( 1.txt , 2.txt )
13 os.remove(file name) import os Remove the file.
os.remove("1.txt")

2
`
Example Programs:
Program 1: Opening and Closing a file "MyFile.txt

file1 = open("MyFile.txt","a")
file1.close()

Program 2: To create a text file by name sample and text is written to it

file = open('sample.txt','w')
file.write("hello")
file.close()

# text file sample is read and content displayed


file = open('sample.txt','r')
print(file.read()) # read the file sample and diplay the output
file.close()

output:
hello

Program 3: # Program to show various ways to read and write data in a file.

file1 = open("myfile.txt","w")
L = ["This is Delhi \n","This is Paris \n","This is London \n"]
file1.write("Hello \n")
file1.writelines(L)
file1.close() #to change file access modes
file1 = open("myfile.txt","r")
print("Output of Read function is ")
print(file1.read())
# seek(n) takes the file handle to the nth byte from the beginning.
file1.seek(0)
print( "Output of Readline function is ")
print(file1.readline())

file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
file1.close()

Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Program 4: To display the modes of file


f=open("1.txt","r")
print(f.name)
print(f.closed)
print(f.mode)
f.close()
print(f.closed)

3
`
5.1.2. FORMAT OPERATOR (String formatting)
String formatting is the process of inserting formats in the output statement for
presenting the values. There are two different ways to perform string formatting
in Python:
Formatting with % Operator.
Formatting with .format() method
a.Formatting with % Operator:
The format operator, % allows us to construct strings, replacing values in
required format. When applied to integers, % is the modulus operator. But when
the first operand is a string, % is the format operator.

Format character Description


%c Character
%s String formatting
%d Decimal integer
%f Floating point real number

Eg :
print('There are %d parrots' %4)
print('The value of pen is Rs. %5.2f' %(30.500))
print("Hey, %s!" % "girls")

output:
There are 4 parrots
The value of pen is Rs. 30.50
Hey, girls!

b. Formatting with .format() method

The .format() method formats the specified values and insert them inside the string's placeholder.
The placeholder is defined using curly brackets { }.

Example 1 :
print("My name is {}, I'm {}".format("John",36))
output :
My name is John, I'm 36

Example 2:
print("My name is {fname}, I'm {age}".format(fname = "John", age = 36))
My name is John, I'm 36

Example 3:
print("My name is {0}, I'm {1}".format("John",36))
output :
My name is John, I'm 36

Formatting in files :
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.

Convert No into string: Output


x = 52 52
f.write(str(x))

4
`
Program to write in a file using format operator Output

f = open('test1.txt','w') 52
x = 52 The value of pi is: 3.1416
f.write(str(x)) my age is 36
f.write('\nThe value of pi is: %5.4f\n' %(3.141592))
f.write("\n my age is {age}".format(age = 36))
f.close()

5.2 COMMAND LINE ARGUMENT


● The command line argument is used to pass input from the command line to the
program when the program is executed.
● Handling command line arguments with Python need sys module.
● sys module provides information about constants, functions and methods of the
python interpreter.
o argv[ ] is used to access the command line argument. The argument list
starts from 0. In argv[ ], the first argument always the file name
o sys.argv[0] gives file name
o sys.argv[1] provides access to the first input
Example 1 Output
import sys C:\Python310>python demo.py
print( “file name is %s” %(sys.argv[0])) the file name is demo.py
Eg 2 : addition of two num Output
import sys C:\Python310>python sum.py 2 3
a= sys.argv[1] sum is 5
b= sys.argv[2]
sum=int(a)+int(b)
print("sum is",sum)
Eg 3 : Word occurrence count Output
using command line arg:
from sys import argv C:\Python310>python word.py
a = argv[1].split() "python is awesome lets program in python"
dict = {}
for i in a: {'lets': 1, 'awesome': 1, 'in': 1, 'python': 2,
if i in dict: 'program': 1, 'is': 1}
dict[i]=dict[i]+1 7
else:
dict[i] = 1
print(dict)
print(len(a))

5
`
5.3. ERRORS AND EXCEPTION

5.3.1 ERRORS
Errors are the mistakes in the program also referred as bugs. They are almost
always the fault of the programmer. The process of finding and eliminating errors is called
debugging. Errors can be classified into three major groups:
1. Syntax errors
2. Runtime errors
3. Logical errors

1. Syntax errors
❖ Syntax errors are the errors which are displayed when the programmer do
mistakes when writing a program.
❖ When a program has syntax errors it will not get executed.
❖ Common Python syntax errors include:
● leaving out a keyword
● putting a keyword in the wrong place
● leaving out a symbol, such as a colon, comma or brackets
● misspelling a keyword
● incorrect indentation
● empty block
2. Runtime Errors
● If a program is syntactically correct that is, free of syntax errors it will be run by the Python
● Interpreter
● However, the program may exit unexpectedly during execution if it encounters a
runtime error.
● When a program has runtime error, it will get executed but it will not
produce output.
● Common Python runtime errors include
● division by zero
● performing an operation on incompatible types
● using an identifier which has not been defined
● accessing a list element, dictionary value or object attribute which does
not exist
● trying to access a file which does not exist
3. Logical errors
● Logical errors occur due to mistake in program’s logic, these errors are difficult to
fix.
● Here program runs without any error but produces an incorrect result.
● Common Python logical errors include
a. using the wrong variable name
b. indenting a block to the wrong level
c. using integer division instead of floating-point division
d. getting operator precedence wrong
e. making a mistake in a boolean expression

6
`
5.3.2 EXCEPTIONS

● An exception (runtime time error) is an error, that occurs during the execution of
a program that disrupts the normal flow of the program's instructions.
● When a Python script raises an exception, it must either handle the exception
immediately otherwise it terminates or quit.

S.No. Exception Name Description


1 FloatingPointError Raised when a floating point calculation fails.
2 ZeroDivisionError Raised when division or modulo by zero takes place for
all numeric types.
3 ArithmeticError All errors that occur for numeric calculation

4 ImportError Raised when an import statement fails.


Raised when a calculation exceeds maximum limit
5 OverflowError for a numeric type
6 IndexError Raised when an index is not found in a sequence
7 KeyError Raised when the specified key is not found in the
dictionary.
8 NameError Raised when an identifier is not found in the local or
global namespace
Raised when an input/ output operation fails, such as the
9 IOError
print statement or the open() function when trying to
open a file that does not exist.
10 SyntaxError Raised when there is an error in Python syntax.
11 IndentationError Raised when indentation is not specified properly.
Raised when the interpreter finds an internal problem,
12 SystemError
Raised when Python interpreter is quit by using the
13 SystemExit
sys.exit() function. If not handled in the code, causes the
interpreter to exit.
14 TypeError Raised when an operation or function is attempted that
is invalid for the specified data type.
Raised when the built-in function for a data type has the
15 ValueError
valid type of arguments, but the arguments have invalid
values specified.
16 RuntimeError Raised when a generated error does not fall into any
category.

7
`
5.4. Handling Exception

❖ Exception handling is done by try and except block.


❖ Suspicious code that may raise an exception, this kind of code will be placed in
try block.
❖ A block of code which handles the problem is placed in except block.
❖ If an error is encountered, a try block code execution is stopped and control
transferred down to except block

Catching exceptions

1. try…except
2. try…except…inbuilt exception
3. try… except…else
4. try…except…else….finally
try…raise..except..
1. try ... except
❖ First try clause is executed. if no exception occurs, the except clause is skipped
and execution of the try statement is finished.
❖ If an exception occurs during execution of the try clause, the rest of the try
clause is skipped.

Syntax
try:
code that create exception
except:
exception handling statement

Example: Output
try: enter age:8
age=int(input("enter age:")) ur age is: 8
print("ur age is:",age) enter age:f
except: enter a valid age
print("enter a valid age")

try…except…inbuilt exception

❖ First try clause is executed. if no exception occurs, the except clause is


skipped and execution of the try statement is finished.
❖ if exception occurs and its type matches the exception named after the except
keyword, the except clause is executed and then execution continues after
the try statement
8
`
Syntax
try:
code that create exception
except inbuilt exception:
exception handling statement

Example: Output
try: enter age: d
age=int(input("enter age:")) enter a valid age
print("ur age is:",age)
except ValueError:
print("enter a valid age")

3. try ... except ... else clause

● Else part will be executed only if the try block does not raise an exception.
● Python will try to process all the statements inside try block.
● If error occurs, the flow of control will immediately pass to the except block and
remaining statement in try block will be skipped.

Syntax
try:
code that create exception
except:
exception handling statement
else:
statements

Example program Output


try: enter your age: six
age=int(input("enter your age:")) entered value is not a number
except ValueError: enter your age:6
print("entered value is not a number") your age is 6
else:
print("your age :” ,age)

4 try ... except…finally

A finally clause is always executed before leaving the try statement, whether
an exception has occurred or not.

9
`
Syntax
try:
code that create exception
except:
exception handling statement
else:
statements
finally:
statements

Example program Output


try: enter your age: six
age=int(input("enter your age:")) entered value is not a number
except ValueError: Thank you
print("entered value is not a number") enter your age:5
else: your age is 5
print("your age :”,age) Thank you
finally:
print("Thank you")

5 try…raise..except (Raising Exceptions)

In Python programming, exceptions are raised when corresponding errors occur at


run time, but we can forcefully raise it using the keyword raise.
Syntax
try:
code that create exception
raise exception
except
exception handling statement
else:
statements

Example: Output:
try: enter your age:-7
age=int(input("enter your age:")) age cannot be negative
if (age<0):
raise ValueError
except ValueError:
print("age cannot be negative")
else:
print("your age is: “,age)

10
`
5.5. MODULES
❖ A module is a file containing Python definitions, functions, statements and
instructions.
❖ Standard library of Python is extended as modules.
❖ To use modules in a program, programmer needs to import the module.
❖ Once we import a module, we can reference or use to any of its functions or
variables in our code.
❖ There is large number of standard modules also available in python.
❖ Standard modules can be imported the same way as we import our user-defined
modules. We use:
❖ 1. import keyword
❖ 2. from keyword

import keyword
import keyword is used to get all functions from the module.
Every module contains many function.
To access one of the function, you have to specify the name of the module and the
name of the function separated by dot. This format is called dot notation.
Syntax:
import module_name
module_name.function_name(variable)

Eg:
Importing builtin module
import math
x=math.sqrt(25)
print(x)
Importing user defined module:
import cal
x=cal.add(5,4)
print(x)

from keyword:
from keyword is used to get only one particular function from the module.

Syntax:
from module_name import function_name
Eg:
Importing builtin module
from math import sqrt
x=sqrt(25)
print(x)

Importing user defined module


from cal import add
x=add(5,4)
print(x)

11
`
math-mathematical module
mathfunctions description
math.ceil(x) Return the ceiling of x, the smallest integer greater than or equal
to x
math.floor(x) Return the floor of x,the largest integer less than or equal to x.
math.factorial(x) Return x factorial
math.sqrt(x) Return the square root of x
math.log(x) Return the natural logarithm of x

math.log10(x) Returns the base-10 logarithms


math.log2(x) Return the base-2 logarithm
math.sin(x) Returns sin of x radians
math.cos(x) Returns cosine of x radians
math.tan(x) Returns tangent of x radians
math.pi The mathematical constant π=3.141592

OS module
❖ The OS module in python provides functions for interacting with the operating
system
❖ To access the OS module have to import the OS module in our program

import os
method example description
os.name os.name This function gives the name of the
Operating system.
os.getcwd() os.getcwd() returns the Current Working
'C:\\Python34' Directory(CWD) of the file used to
execute the code.
os.mkdir(folder) os.mkdir("python") Create a directory(folder) with the
given name.
os.rename(oldname, os.rename( python , pspp ) Rename the directory or folder
new name)
os.remove( folder ) os.remove( pspp ) Remove (delete) the directory or
folder.
os.getuid( ) os.getuid( ) Return the current process s user id

os.environ os.environ Get the users environment

12
`
sys module
❖ Sys module provides information about constants, functions and methods.
❖ It provides access to some variables used or maintained by the interpreter.
import sys
method example description
sys.argv Provides The list of command line
sys.argv
arguments passed to a Python script
sys.argv[0] Provides to access the file name
sys.argv[1] Provides to access the first input
sys.path sys.path It provides the search path for modules
sys.path.append() sys.path.append() Provide the access to specific path to
our program
sys.platform sys.platform Provides information about the
'win32' operating system platform
sys.exit sys.exit Exit from python
<built-in function
exit>

Steps to create the own module


Here we are going to create calc module: our module contains four functions they
are add(),sub(),mul(),div()

Program for calculator module Output.py


Module name : calc.py
import calc
def add(a,b):
print(a+b) calc.add(2,3)
def sub(a,b):
print(a-b) Output
def mul(a,b):
print(a*b)
def div(a,b):
print(a/b)

5.6. PACKAGES
● A package is a collection of Python modules.
● Module is a single Python file containing function definitions; a package is a directory
(folder) of Python modules containing an additional __init_.pyfile, to differentiate a
package from a directory.
● Packages can be nested to any depth, provided that the corresponding directories
contain their own __init__.py file.
13
`
● __init__.py file is a directory indicates to the python interpreter that the directory should
be treated like a python package.__init__.py is used to initialize the python package.

● A package is a hierarchical file directory structure that defines a single python


application environment that consists of modules, sub packages, sub-sub packages and
so on.
● _init_.py file is necessary since Python will know that this directory is a python package
directory other than ordinary directory
Steps to create a package
Step 1: Create the Package Directory: Create a directory (folder) and give it your package's
name. Here the package name is calculator.

Step 2: write Modules for calculator directory add save the modules in calculator directory.
Here four modules have created for calculator directory.

Step 3: Add the __init__.py File in the calculator directory .


A directory must contain a file named _init_.py in order for Python to consider it as a
package.
Add the following code in the __init__.py file.

14
`

Step 4:To test your package in your program and add the path of your package in your program by
using sys.path.append(). Here the path is C:\python34

ILLUSTRATIVE PROGRAMS
1. Program to copy from one file to another

fs=open("First.txt","r")
fd=open("Dest.txt","w")
fdata = fs.read()
fd.write(fdata)
print("File copied sucessfully!!!")
fs.close()
fd.close()

2. Program to count no of words in a file

fs = open("First.txt","r")
fdata = fs.read()
L = fdata.split()
count=0
for i in L:
count=count+1
print("Total no of words in the file: ",count)
fs.close()

15
`
3 Program to validate Voter’s age

try:
Name = input("Enter name : ")
Age = int(input("Enter Age : "))
if(Age<0):
raise ValueError
elif (Age>=18):
print(Name, " is eligible for voting.")
else:
print(Name," is not Eligible for voting.")
except (ValueError):
print("Value Error: invalid Age value.")

4. Program to validate Student’s mark Range (0-100)

try:
L = ["AAA",100,30,80,90,50]
Name = L[0]
marklist = [int(m) for m in L[1:]]
for mark in marklist:
if(mark<0 or mark>100):
raise ValueError
if (all(m>=50 for m in marklist)):
print(Name, "- Grade - Pass.",end=" ")
print("Total = ", sum(marklist),end=" ")
print("Average = ",round((sum(marklist)/len(marklist)),2))
break
else:
print(Name, "- Grade - Fail.")
break
except (ValueError):
print("Value Error: invalid mark.")

16

You might also like