Unit 5
Unit 5
f.write(‘hello world’)
11 (number of characters written)
f.writeline()
f.writelines(x) x is a list of strings
import os
os.rename(“text1.txt”,”text2.txt”)
os.remove(“text2.txt”)
import os.path
os.path.isfile(“text1.txt”) return True if file exist
Format operators
% operator
x=52
k=’in %g years i have passed %d %s’%(3.5, x , ‘courses’)
print(k)
%d integer
%u unsigned int
%c character
%s string
%f float
%o octal
%x, %X hexadecimal
%e, %E exponential form
%g shorter of %f and %e
%G shorter of %f and %E
print(‘%10f’%12.2346)
12.234600
print(‘%05d’%12)
00012
print(“%+10s”%“cat”) + means right align - for left align default is center align 10
is width
cat
“{:*^8}”.format(“cat”)
**cat***
^ center > right default is left alignment
Here * is padding character. Center alignment. total width 8 character.
import sys
print(len(sys.argv))
print(str(sys.argv))
Errors
Exceptions
Errors detected during execution is called exceptions. Trying to open a file that does not exist,
Divide by Zero, Trying to import non existing module lead to exceptions.
Whatever be the error , python create a exception object. If not handled properly it prints a
traceback to the error along with some details about why the error occurred.
Builtin exceptions
try:
statement
except syntaxerror:
print(“syntax error”)
except zerodivisionerror:
print(“division by zero”)
except: #should be in the last
print(“some other error”)
else:
print(“no exception”)
finally:
print(“over”)
else and finally are optional. Finally block is used for doing concluding tasks like closing file
resources.
Raising exception
ex=runtimeerror(“wrong argument type”)
raise ex
Modules
User can write a .py file having the definitions of all the functions needed to perform common
tasks like mathematical operations. We can import this module in another program and access
variables and methods by using module_name.var. Module must be in the same directory as
that of program in which it is imported.it can be in one of the die=rectories listed under sys.path
math module
Contain builtin functions like
sqrt() sqrt(64) 8
floor() eg print(floor(3.87)) 3
ceil() eg print(ceil(3.17)) 4
Pi
datetime module
import datetime
tdate= datetime.date.today()
print(tdate)
c=datetime.datetime.now()
print(c.year)
print(c.month)
print(c.day)
print(c.hour)
print(c.minute)
print(c.second)
Packages
Arrange related modules in a tree like hierarchy for easier access. Python package have
directories. Each directory may have subdirectories and files(modules). Each directory must
contain a file named __init__.py to consider it as a package. This file can be an empty file.
Database
Is a file that is organized for storing data. Similar to dictionary but stored in disc so that value
is not lost even after the program ends.
import dbm
db=dbm.open(‘captions’, ’c’) # ‘c’ will create if not existing
db[‘jack.png’] #db is database object
b’photo of john jack #its a byte object
db[‘jack.png’]=”hello” #older content get overwritten
Pickling
Write method of file object accept only strings. Pickling is a process of converting an object in
memory to a byte stream that can be stored in a disc. It is also called serialization, flattening or
marshalling. The reverse process is called unpickling.In binary files writing is also called as
dumping and reading is called loading. Picking can be done with all datatypes like int, float,
string, list, tuple, set and dictionary.
import pickle
emp={1:’a’,2:’b’,3:’c’,4:’d’,5:’e’}
pickling_on=open(“emp.pickle”, ’wb’)
pickle.dump(emp, pickling_on)
pickling_on.close()
pickle_off=open(“emp.pickle”,’rb’)
emp=pickle.load(pickle_off)
print(emp)