Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Python Unit - 5

Uploaded by

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

Python Unit - 5

Uploaded by

prvnraj2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Rraveon

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
prograns: wordcount, copy file, Voter's age validation,Marks range validation (0-100).
FILES AND EXCEPTIONS
FILES
File is ananmed 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 Abinary files store the data in the binary
can be sequentially processed by a format (i.e. 0 s and 1 s)
Computer in forward direction.
Each line is terminated with aspecial It contains any type of data ( PDF,
character, called the EOL [End of images, Word doc,Spreadsheet, Zip
Line character] files,etc)
Operations on Files
InPython, 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(string) f.read()
4. Close a file
Syntax

file_object.close) f.close()
modes description
read only mode
W write only
appending mode
r+ read and write nmode
W+ write and read mode
Differentiate write and append mode
write mode append mode
It is usedto write a string into a file. It is used to append (add) a string into a file.
If file is not exist it creates a new file. If file is not exist it creates a new file.
If file is exist in the specified name, the It willadd 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
f.write(string) f.write("hello") Writingastring into a file.
f.writelines ("1st line \n Writes a sequence of strings to
2
f.writelines(sequence) second line") the file.
f.read() #read entire To read the content of a file.
3
f.read(size) file f.read(4) #read the
first 4 chr
f.readline() f.readline() Reads one line at a time.
5
f.readlines() f.readlines() Reads the entire file and returns a
list of lines.
f.seek(offset,[whence]) Move the file pointer to the
fseek(0) appropriate position. It sets the
[whence value is optional.] file pointer to the starting of the
file.
[whence =0 from f.seek(3,0) Move three characters from the
6 beginningl beginning.
[whence =1 from current Move three characters ahead from
position] f.seek(3,1) the current position.
[whence =2 from last f.seek(-1,2) Move to the first character from
position] end of the file
7
f.tell() f.tell() Get the current file pointer
position.
f.flush() f.flush() To flush the data before closing
any file.
f.close( ) f.close() Close an open file.
10 f.name( ) f.name( ) Return the name of the file.
11 fmode() 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")
5.1.2. 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.

Convert No into string: Output


X= 52 52
f.write(str(x))
Convert to strings using format operator, % Example:
print ( format string %(tuple of values) >>>age=13
file.write( format string %(tuple of values) >>>print( " age is %d "%age)
age is 13
Program towrite even number in a file using Output
format operator
enter n:4
enter number:3
f=open("t.txt""w")
enter number:4
n=eval(input("'entern:")
enter number:6
for iin range(n):
enter number:8
a=int(input("enter number:")
if(a%2==0):
result in file t.txt
f.write(str(a))
4
f.close()
6

Format character Description


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

COMMAND LINE ARGUMENT


The command line argument is used to pass input from the command line to your
program when they are started to execute.
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
sys.argv[0] gives file name
sys.argv[1] provides access to the first input

Example 1 output
importsys 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 23
a= sys.argv(1) sum is5

b= sys.argv(2]
sum=int(a) +int(b)
print("'sum is",sum)
Eg 3: Wordoccurrence count Output
using comment linearg:
from sys import argv C:\Python34>python word.py
a = argv[1].split() "python isawesome lets program in python"
dict = }
for i in a: ('lets': 1,'awesome': 1, 'in': 1, 'python': 2,
ifi in dict: 'program': 1, 'is': 1}
dict[i]=dict[i]+1 7

else:
dict[i] = 1
print(dict)
print(len(a))

ERRORS AND EXCEPTION

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
programmer do
Syntax errors are the errors which are displayed when the
mistakes when writing a program.
P qy(m
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 akeyword
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 Pvthon
Interpreter
bd olpt
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 exiist
trying to access a file which does not exist
3. Logical errors
" Logical errors occur due to mistake in program's logic, these errorsare 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 Ccto
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.
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 anumeric type

6 IndexError Raised when an index is not found in a sequence


7 KeyError Raised when the specified key isnot found inthe
|dictionary.
8 NameError Raised when an identifier is not found inthe localor
|global namespace
|Raised when an input/ output operation fails, such as the
|lOError print statement or the open() function when trying to
open a file that does not exist.
10 SyntaxError |Raisedwhen 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
but when this error is encountered the Python
|interpreter does not exit.
13 Raised when Python interpreter is quit by using the
|SystemExit
sys.exit(0 function. If not handled in the code, causes the
interpreter to exit.
14 TypeError |Raisedwhen an operation or function is attempted that
is invalid for the specified data type.
15 ValueError
Raised when the built-in function for a data type has the
valid type of arguments, but the arguments have invalid
values specified.
16 RuntimeError Raised when agenerated error does not fall into any
category.
Handling Exception
* Exception handling is done by try and except block.
aleh
Suspicious code that nmay raise an exception, this kind of code will be placed in
try block.
Ablock of code which handles the problem is 2 ti s
placed in except block. laucr
try block except block
faster
code that may code that
create exception handle exception Theclo
de
is
ly
fie

Try Raise Except


Exception may Ralse thc Exception Catch ie exception occurs
0ccur
(onsume or

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
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...nbuilt exception
First try clause is executed. if no exception occurs, the except clause is
skipped and execution of the try statement is finished.
ifexception 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

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

Elsepart will be executed only if the try block does not raise an exception.
Python willtry 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
try: Output
enter your age: six
age=int(input("enter your age:"))
except ValueError: entered value is not a number
enter your age:6
else:
print("entered value is not a number") your age is 6
print("your age :" ,age)

4 try ... except...finally


A finally clause is always
an exception has occurred or not. executed before leaving the try statement, whether
Syntax
try:
code that create exception
except:
exception handling statement
else:
statements
finally:
statemnents

Example program Output


try: enter your age: six
age=int(input("enter your age:")) entered value is not anumber
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 handlingstatement
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)

MODULES
Amodule is a file containing Python definitions, functions, statements and
instructions.
4 Standard library of Python isextended 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 inour 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
importkeyword 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 nmath
X=math.sqr(25)
print(x)
Importing user defined module:
import cal
X=cal.add (5,4)
print(x)
2. from keyword:
trom 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)

math-mathematical module
mathfunctions description
math.ceil(x) |Return the ceiling of x, the smallest integer greater than orl2<*
equal tox
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 ofx radians

|math.pi IThe mathematical constant r=3.141592

OS module
The OS module in python provides functions for interacting with the operating
system
Toaccess the OS module have to import the OS module in our program
importos
method example description
the
os.namne 0S.name This function gives the name of
Operating system.
os.getcwd() returns the Current Working
os.getcwd)
'C:\\Python34' Directory(CWD) of the file used to
execute the code.
with the
Os.mkdir("python") Create a directory(folder)
os.mkdir(folder)
given name.
Rename the directory or folder
Os.rename(oldname, 0s.rename python,pspp )
new name) directory or
Remove (delete) the
os.remove( folder ) os.remove(pspp )
folder.
process s user id
Return the current
os.getuid()
os.getuid()
environment
Get the users
os.environ
OS.environ

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

module thev
the own module contains four functions
Steps to create create calcmodule: our
Here we are going to
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) 5

def div(a,b):
print(a/b)

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 isused to initialize the python package.
Apackage 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.

Name Date modfied Type

-Pycache 20 09 2017 1356 Fle folder


calculator 24-11-2017 13.48 Fsie foider
. DLLs 18-08-2017 08 59 Eile folder

Step 2: write Modules for calculator directory add save the modules in calculator directory.
Here four modules have created for calculator directory.
Local Disk {C Python34 calcutor
Share with Burn Niew folder

Narme Date modtied Type


Python fde IKB
Padd
K8
P d 241101713 5) Python Fie
1 KB
Pmul 2411-2017 1353 Python fie
1 KB
2411-20171353 Python Fle
Psut

div.py
add.py sub.py mul.py
def mul(a,b): def div(a,b):
Ste def add(a,b): |def sub(a,b): print(a/b)
print(a+b) print(a-b) print(a"b)
p 3:
Ad

the_init_.py File in the calculator directory to consider it as a


directory must contain a file named init .py in order for Python
A
package. the_init_.py file.
Add the following code in
Python 3.4.1:_init py - CAPythor
File Edit Format Run ptions
add p add
sub pc sub
mul p- mul
div nper div

Python34 caiculator
Local Disk (C
Share eth Surn New foldes
brary
Date rncdited Tvpe
Name
24 1 1 1400 Python File
P,thon Fúe
4110:i351 Python Fie
241120:i353 Pthon Fe
411 201'1353 Phon Fle
sut

program by
test your package in your program and add the path of your package in your Here the
Step 4:To
using sys.path.append).
path is C:\python34
Aython 34l outputpy -CPythona4/calculator/outputpy
File Edit Format Run Options Windows Help
calculator

8y3.path. append (
calculatox. ada(5,)})
1a)Program to count theno. of words
str=input(Cgive the string")
words =strsplit()
Count=0
for w in words:
Count=Count+ 1
print(count)
Input : Welcometo College.College is in chennaicity
Output: 9

1b) Program to count the no. of occurrences of word(frequency of wordin a text)


str=input("give the string")
words = str.split(0
count dict)
for w in words:
if w in count:
count[w] += 1
else:
count[w] = 1
print(count)

Input :Welcome to College. College isin chennai city


Output: (Welcome': 1, 'to':1, College':2)"!: 1, 'is':1,'in': 1, 'chennai':1,'city': 1)
2a Copy a file
f1=open("1.txt","r")
f2=open("2.txt","w")
for iin f1:
f2.write(i)
f1.close()
f2.close()
Output
no output. internally the content in f1 willbe copied tof2
2b Copy and display contents
f1=open("1.txt""")
f2=open("2.txt", "w+")
for i in f1:
f2.write()
f2.seek(0)
print(f2.read())
f1.close()
f2.closc()
Output
Hello welcome to python programming
(content in f1 and f2)

3. Voter's age validation


age = int(input('Enter age of a user: ))
if age >= 18:
print('User is eligible for voting: ", age)
else:
print(User isnot eligible for voting:', age)
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
4 Marks range validation (0-100).
mark=int (input('Enter the mark:))
if mark<0 or mark>100:
print(The mark isout of range,try again')
else:
print(The mark is in the range')

Output:
Enter the mark: 98
The mark is in the range
Enter the mark: 198
The mark is out of range, try again

You might also like