GE3151_PYTHON_UNIT_5
GE3151_PYTHON_UNIT_5
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).
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
1. Open a file
Syntax: Example:
file_object=open(“ file_name.txt” , mode ) f=open( “sample.txt” , ‘w ‘)
2. Write a file
Syntax: Example:
file_object.write(string) f.write( ‘hello’ )
file_object.close()
3. Read a file
Syntax
file_object.read() f.read( )
4. Close a file
Syntax
file_object.close() f.close()
modes description
r read only mode
w write only
a appending mode
r+ read and write mode
w+ write and read mode
Differentiate write and append mode
Example 1 Output
import sys 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 sam@sam~$ 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 comment line arg:
from sys import argv C:\Python34>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))
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
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.
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.
Catching exceptions
1. try…except
2. try…except…inbuilt exception
3. try… except…else
4. try…except…else….finally
5. 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")
2. try…except…inbuilt exception
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("Your age is:",age)
except ValueError:
print("enter a valid age")
● 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
A finally clause is always executed before leaving the try statement, whether
an exception has occurred or not.
Syntax
try:
code that create exception
except:
exception handling statement
else:
statements
finally:
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)
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
1. 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)
2. 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)
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
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
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>
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.
● 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.
Step 2: write Modules for calculator directory add save the modules in calculator directory.
Here four modules have created for calculator directory.
Step 2: 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 apackage.
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
1 a)Program to count the no. of words
Output: 9
print(count)
2a Copy a file
f1=open("1.txt","r")
f2=open("2.txt","w")
for i in f1:
f2.write(i)
f1.close()
f2.close()
Output
no output. internally the content in f1 will be copied to f2
f1=open("1.txt","r")
f2=open("2.txt","w+")
for i in f1:
f2.write(i)
f2.seek(0)
print(f2.read())
f1.close()
f2.close()
Output
Hello welcome to python programming
(content in f1 and f2)
Output 1
Enter age of a user: 25
User is eligible for voting: 25
Output 2
Enter age of a user: 13
User is not eligible for voting: 13
Output: