Unit 5
Unit 5
EXAMPLE:
f = open("abc.txt","w")
Mode Name
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:
writable()-> Returns boolean value indicates that whether file is writable or not
Writing Data to Text Files: We can write character data to the text files by
using the following 2 methods.
1. write(str)
2. writelines(list of lines)
File Operations – tell() method
• tell() method returns the current position of the
file handle.
• Syntax:
file_object.tell()
File Operation – with/as method
• Syntax:
with file_creation as file_object:
block of statements
• Eg: output:
with open(“test.txt”) as f:
for line in f:
print(line.strip())
Format operator
• f.write(‘%s’ %‘Python’) Prints Python to the
file
• f.write(‘%d %d %s’ %(3, 5,‘Values’)) Prints 3
5 Values to the file
• f.write(“I am studying %dst year in dept of %s at
%s college” %(1, ‘IT’, ‘KSRIET’)) Prints I am
studying 1st year in dept of IT at KSRIET
college to the file.
S.No Syntax Example Description
import sys
a= sys.argv[1]
sam@sam~$ python.exe sum.py
b= sys.argv[2]
sum=int(a)+int(b)
2 3 sum is 5
print("sum is",sum)
Errors and Exceptions
• Errors:
Two types:
Syntax Errors
Logical errors
Syntax Errors
• Also known as parsing errors.
• It is the common mistakes that we make while
typing the programs.
Exceptions
• Exceptions are unexpected events that occur during the
execution of a program.
• Mostly occurs due to logical mistakes.
• The python interpreter raises an exception if it encounters an
unexpected condition like running out of memory, dividing by
zero, etc.
• These exceptions can be caught and handled accordingly.
• If uncaught, the exceptions may cause the interpreter to stop
without any notice.
Errors
ZeroDivisionError
TypeError
ValueError
FileNotFoundError
EOFError
SleepingError
IndexError
KeyError
Error Example
a=int(input("Enter a number:"))
Exception Handling
Exception handling is done by try and catch block.
Suspicious code that may raise an exception, this kind of code will be
•try…except
•try…except…inbuilt exception
•try… except…else
•try…except…else….finally
•try.. except..except...
•try…raise..except..
try ... Except
• In Python, exceptions can be handled using a try statement.
1.A critical operation which can raise exception is placed inside the try clause
and the code that handles exception is written in except clause.
2.It is up to us, what operations we perform once we have caught the
exception.
3.Here is a simple example.
try…except …in built exception
Syntax
try:
code that create exception except:
exception handling statement else:
statements finally: statement
try …except…except… exception :
1.It is possible to have multiple except blocks for one try block.
Let us see Python multiple exception handling examples.
Syntax:
>>> raise error name
Example: Output:
def
floordiv(a,b):
c=a//b
print(c)
Output:
The value of pi is : 3.141592653589793
from … import statement
• Python’s from statement helps to import specific
attributes from a module into the current program.
• Syntax:
from modulename import name1[,name2,
…]
• Eg:
from calci import add, sub
• Here only the add and sub functions alone are
imported from calci module instead of entire module.
• Also from calci import * can be used to import all
functions to the python program.
PACKAGES
• A package is a collection of python modules.
• Eg: Pygame, Turtle, etc,.
• These are the separate software packages that can
be imported into our python program.
• These packages in turn contains several modules to
produce the expected results.
Step 1: Create the Package Directory
Step 2: write Modules for calculator directory
add save the modules in calculator directory.
Step 3 :Add the following code in the
_init_.py file
Step 4: To test your package
ILLUSTRATIVE PROGRAMS
Word count Output
import sys
a = argv[1].split() C:\Python34>python .exe word.py
dict = {} "python is awesome lets
for i in a: program in python"
if i in dict: {'lets': 1, 'awesome': 1, 'in': 1,
dict[i]=dict[i]+1 'python': 2,
else: 'program': 1, 'is': 1}
dict[i] = 1 7
print(dict)
print(len(a))
Copy a file Output
f1=open("1.txt","r") no output
f2=open("2.txt“,w") internally the content in f1
for i in f1: will be copied to f2
f2.write(i)
f1.close()
f2.close()
copy and display contents Output
f1=open("1.txt","r") hello
f2=open("2.txt","w+ welcome to python
") for i in f1: programming
f2.write(i)
f2.seek(0) (content in f1 and f2)
print(f2.read())
f1.close()
f2.close()
Voters Age Validation
try:
age=int(input(“Enter Your Age:”))
if age>18:
print(“Eligible to vote!!!”)
else:
print(“Not eligible to vote!!!”)
exceptValueError as err:
print(err)
finally:
# Code to be executed whether exception occurs or not
# Typically for closing files and other resources
print(“Good Bye!!!”)
• Output1:
• Enter Your Age: 20
• Eligible to vote!!!
• Good Bye!!!
•
• Output2:
• Enter Your Age: 16
• Not eligible to vote!!!
• Good Bye!!!
Marks Range Validation (0-100)
whileTrue:
try:
num = int(input("Enter a number between 1 and 100:
"))
if num in range(1,100):
print("Valid number!!!")
break
else:
print (“Invalid number. Try again.”)
except:
print (“That is not a number. Try”)
Output:
Enter a number between 1 and 100: -1
Invalid number.
Try again.
Enter a number between 1 and 100: 1000
Invalid number.
Try again.
Enter a number between 1 and 100: five
This is not a number. Try again.
Enter a number between 1 and 100: 99
Valid number!!!