UNIT V Hint
UNIT V Hint
Closing a file
close( ) – At the end of the program the opened file should be closed using close( ) built in function.
Syntax to close a file : fileobject.close( )
Example : f1.close( )
4. Writing to a file - To write into a file, it is needed to open a file with access modes like ‘w’,’wb’,’w+’,’wb+’,’a’,’ab’,’a+’,’ab+’
write( ) – Writing a string or sequence of bytes (for binary files) is using write( ) method.
Syntax to write a file : fileobject.write(string)
abc.txt file
Example : f1=open(“abc.txt”,”w”) python programming
str=”python programming”
f1.write(str)
f1.close( )
Reading from a file - To read from a file, it is needed to open a file with access modes like ‘r,’rb’,’r+’,’rb+’
(i) Reading a file using read(size) method – Read all the lines of the text file & displays them line by line
Syntax to read a file : fileobject.read(size)
Example : f1=open(“abc.txt”,”r”) abc.txt file input output
str=f1.read( 7) python programming programming
problem solving problem solving
print(str) analysis and design analysis and design
f1.close( )
(ii) Reading a file using readline( ) method – Read all the lines in to list and displays with “\n” newline character
Syntax to read a file : fileobject.readline( )
Example : f1=open(“abc.txt”,”r”) abc.txt file input output
str=f1.readline( ) python programming [‘python programming\n’,‘problem
problem solving solving\n’,’analysis and design\n’]
print(str) analysis and design
f1.close( )
(iii) Reading a file using for loop – A file can be read line-by-line at a time using for loop
Syntax to read a file : for iterating_var in fileobject:
abc.txt file input output
Example : f1=open(“abc.txt”,”r”) python programming python programming
for line in f1: problem solving problem solving
print(line, end=” “) analysis and design analysis and design
f1.close( )
A Python program to count number of lines, words & characters in a text file
import os,sys
fname=input(“Enter file name”) abc.txt file input
if(os.path.isfile(fname)): python programming
f1=open(“fname”,”r”) problem solving
else: analysis and design
print(fname+”does not exist”)
sys.exit( )
Output
cl=cw=cc=0 Enter file name abc.txt
for line in f1: Number of lines: 3
words=line.split( ) Number of words: 7
cl=cl+1 Number of characters : 55
cw=cw+len(words)
cc=cc+len(line)
print(“Number of lines: %d Number of words: %d Number of characters : %d” %(cl,cw,cc))
f1.close( )
A Python program for copying a file
f1=open(“oldfile.txt”,”r”) oldfile input newfile input
f2=open(“newfile.txt”,”w”) python programming python programming
str=f1.read( ) problem solving problem solving
f2.write(str) analysis and design analysis and design
fl.close( )
5. Format operator – 1. Format operator is an operator ( % ), that takes a format string. 2. The argument of write should to
be a string. To put other values in a file, they have to be converted to strings
%d – Formatted to an integer, %g – Formatted to a floating-point integer, %s – Formatted to a string
Eg: apple=15; print("I have %d apple in my pocket" %apple) Output : I have 15 apple in my pocket
Eg: print("In %d years I have spotted %g %s" %(2,0.5,'parrot')) Output : In 2 years I have spotted 0.5 parrot
6. Command line arguments – Another method of input statements is uses command line arguments. It can be processed
by using sys module. Multiply all the values given to the function as parameter
sys.argv is the list of command line arguments. def mulitplyall(*values)
len(sys.argv) is the number of command line arguments. mul=1
*args – It will give us all the function parameters in the form of a list print(values)
**kwargs – It will give us all the keyword arguments for i in values:
import sys mul=mul*i
a=int(sys.srgv[1]) output print(“The multiplication of 5 X 2 is “, mul)
b=int(sys.argv[2]) python add.py 5 10 multiplyall(5,2)
c=a+b 15
print(c) Output The multiplication of 5 X 2 is 10
7. Errors: Errors are bugs occurred may be compile time or run time.
Types of Errors
Syntax error- Error occurs at Compile Time [keyword named as variable,indent,bracket missing,colon missing]
Logical error- Error occurs at Run Time [division by zero, index out of range, data type conversion]
Semantic error- Error occurs at producing output [unwanted output]
8. Exceptions: Exceptions are unexpected events that occur during the execution of program. An error occurs at runtime
Types of Exceptions at run time
ZeroDivisionError Eg: print(55/0)
IndexError Eg: a = [ ]; print(a[5])
TypeError Eg: tup = ("a", "b", "d", "d"); tup[2] = "c"
FileNotFoundError Eg: try: f = open(filename, "r"); except FileNotFoundError: print("There is no file", filename)
ValueError Eg: number = float(user_input) ; except ValueError:
IOError Eg: : try: f = open(filename, "w"); except IOError: print("Access Denied”)
9. Handling exceptions : To prevent an exception from causing our program to crash, by wrapping the block of code in a
try ... except construct. Raising our own exceptions to detects an error using raise keyword.
try:
print(55/0) # Try do do something that could fail.
except ZeroDivisionError:
print(“Divide by zero error”)# This will be executed if a ``ValueError`` is raised. Multiple except may allowed.
except ValueError:
print(“Value Error”)
else:
print(“No Error”) # This will be executed if not exception got raised in the `try`` statement.
finally: # This block is to ensure that code is always executed
print(“Error may raised or not”) # This will be executed whether or not an exception is raised.
10. Modules - A module is a file containing Python definitions and statements. The filename is the module name with the
suffix.py appended. Inbuilt modules are stored in standard python library like import math, import string, import time
Example inbuilt math module: The math module contains the kinds of mathematical functions like sqrt,sin,cos,log..
Namespaces : A namespace is a collection of identifiers that belong to a module, or to a function.
Scopes: The scope of an identifier is the region of program code in which the identifier can be accessed, or used.
There are three important scopes in Python:
Local scope refers to identifiers declared within a function.
Global scope refers to all the identifiers declared within the current module, or file.
Built-in scope refers to all the identifiers built into Python
import statement - A statement which makes the objects contained in a module available for use within another module.
Here are three different ways to import names into the current namespace, and to use them:
The from…import statement Syntax from math import cos, sin, sqrt
from module import functioname1,name2,..name n x = sqrt(10); print(x)
11. Packages: A package is a directory it has collection of Python modules. Multiple modules in the same directory.
Having a directory of modules allows us to have modules contained within another module. This allows us to use qualified
module names, clarifying the organization of our software.
Directory structure: D:\python\mathematicalprocess\arithmetic.py
D:\python\mathematicalprocess\logical.py