CLASS: XII
Subject: Computer Science (083)
File Handling:
It provides a set of functions using which we can write data in a secondary storage.
Types of files:
i. Text File: It is a sequence of characters written in the file.It has extension .txt,
.ini,.rtf.
ii. Binary File: It is a file which is used to write data in binary form.It has extension
.bin, .dat, .exe. It is used to write python objects like list, tuple, dictionary, etc.
iii. CSV (Comma Separated Values): It is a comma separated sequence of
characters stored in tabular format i.e in the form of rows and columns. TSV is Tab
Seperated Values. NSV is new line Seperaated values. The extension of csv file is
.csv.
open() Method:
filepointer=open(filename,modes)
It is used to open a file. It takes two parameters
i. Filename: It consists of filename and file extension
ii. Second parameter is the mode in which the file gets opened.
Different Types of modes:
r=read. It is a default mode. It will give an error if the file does not exist.
w= write (It will create a file if it does not exist and erase the previous data if file
exists).
a= append (It will create a file if not exist and append the data at the end if file
exists).
r+: read+write (It will open a file in read mode and can be used to write data also).
It will give an error if the file does not exist.
w+: write+read (It will open the file in write mode and can be used to read data
also). It will create a new file if it exists.
a+:append+read (It will open the file in append mode and can be used to read
data)
rb,wb,ab,rb+,wb+,ab+: For binary files
Examples:
i. Write a statement to open a file student.txt in read mode.
x=open('student.txt','r')
ii. WAP to open a file student.dat in write mode
xx=open('student.dat','wb')
iii. In which mode file will open.
x=open('student.txt')
The file will in read mode.
Text Files:
Reading a data:
i.read()
read(): It will return all the data of the file in the form of string.
read(n): It will read the n characters of the file in the form of string.
Example:
Consider a file student.txt , write a Python statements to
a. read all the data of file
b. read the 10 characters from the file
Solution:
a.
f=open(‘student.txt’,’r’)
x=f.read()
print(x)
b.
f=open(‘Student.txt’,’r’)
x=f.read(10)
print(x)
ii. readline() :
a. readline(): It will return one line of text from the file.
b. readline(n): It will return the first n characters of the line.
Example:
Python is a Programming Language.
It has easy syntax
It is an Interpreter based language.
It was developed by Guido Van Rossum.
i. Consider the above file data.txt, write a code that return first line of the
file.
f=open(‘data.txt’,’r’)
x=f.readline()
print(x)
O/P: Python is a Programming Language
ii. Consider a file data.txt, write a code that return 5 characters of the file.
f=open(‘data.txt’,r)
x=f.readline(5)
print(x)
O/P: Pytho
iii. Write a program to read a file Answer.txt and print its characters.
x=open('Answer.txt','r')
s=x.read()
print(s)
print('Total Characters=',len(s))
x.close()
iv. Write a program to read a file Answer.txt and count the total occurrence of
vowels.
x=open('Answer.txt','r')
s=x.read()
c=0
for i in s:
if i in 'AEIOUaeiou':
c=c+1
print(i)
print('Vowels=',c)
x.close()
v. WAP to read the data from student.txt and display the data in reverse order.
s=open('student.txt','r')
data=s.read()
x=data[::-1]
print(x)
s.close()
vi. WAP to read the data from poem.txt and count total words in a file.
s=open('poem.txt','r')
data=s.read()
x=data.split(' ')
print(x)
print('No of words',len(x))
s.close()
vii. WAP to read a file answer.txt print the words in reverse order.
s=open('answer.txt','r')
data=s.read()
x=data.split(' ')
x1=x[::-1]
x2=' '.join(x1)
print(x2)
s.close()
viii. WAP to read a file answer.txt print the words in sorted order.
s=open('poem.txt','r')
data=s.read()
x=data.split(' ')
x.sort()
x=' '.join(x)
print(x)
s.close()
ix. WAP to read data from file answer.txt and count the occurrence of O and H in a
file
#Ex: Hello
#H or o =2
s=open('answer.txt','r')
data=s.read()
c=0
for x in data:
if x in 'HhOo':
c=c+1
print('Total Occurence=',c)
s.close()
X. WAP to read data from answer.txt and search the given word in a file and count
its total occurence.
s=open('answer.txt','r')
data=s.read()
a=data.split(' ')
c=0
m=input('Enter a word')
for x in a:
if x == m:
c=c+1
print('Total Occurrence=',c)
s.close()
xi. WAP to read data from answer.txt and count the occurrence of A-M in a file.
#Eg: Ayush Verma
#A-M=5 if x>='A' and X<="M" or x>='a' and x<='m':
#read(n): It will read n no of characters from the file
s=open('answer.txt','r')
data=s.read(5)
print(data)
data=s.read(6)
print(data)
s.close()
#What is the difference between read() and read(n)?
readline(): It will read one line at a time. It will return
data linewise. Line is denoted newline character (\n).
s=open('answer.txt','r')
data=s.readline()
print(data)
data=s.readline()
print(data)
s.close()
Considering the data of file is
Hello How are you?
Today is Thursday.
We are going through filehandling
readline(n): It will return n characters of the line. IF n
exceeds the no of chars in a line ,it will return a line
s=open('answer.txt','r')
data=s.readline(500) #Hello How are you?
print(data)
data=s.readline(100) #Today is Thursday.
print(data)
s.close()
s=open('answer.txt','r')
data=s.readline(5) #Hello
print(data)
data=s.readline(10) # How are y
print(data)
s.close()
readlines():It returns all the lines in the form of list
s=open('answer.txt','r')
data=s.readlines()
print(data) #['Hello How are you?\n', 'Today is Thursday.\n',
'We are going through filehandling']
data=s.readlines()
print(data) #[]
s.close()
readlines(): It will return till those lines where the nth
character lies.
readlines(5): It will return first line
readlines(50): First two lines.
s=open('answer.txt','r')
data=s.readlines(10)
print(data)
data=s.readlines(15)
print(data)
s.close()
#Write a function def readliness(name) and print all the
lines in seperate line.
def readliness(name):
s=open(name,'r')
data=s.readlines()
for x in data:
print(x)
s.close()
readliness('answer.txt')
def readliness(name):
s=open(name,'r')
d=s.read()
data=d.split('\n')
for x in data:
print(x)
s.close()
readliness('answer.txt')
#Write a function def linelen(data) and total charaters
linewise.
#Write a function def totalwordsline(data) and display total
words linewise.
#Writing data in a file.
write(): It will write a string of text in a file
writelines(): It will write a list of string in a file
WAP to write a line a file abc.txt.
x=open('abc.txt','a')
s=input('Enter a string')
x.write(s)
print('Data Written Successfully')
x.close()
x=open('xyz.txt','w')
d=['Hello How r u','kffgfkgfjdg','dfdfdf' ]
x.writelines(d)
print('Data Written Successfully')
x.close()
Reading and Writing in Binary File
x=open('xyz.dat','rb')
To write a Python objects(classes,list,tuple,dictionary)
It is fast in execution.
module used: pickle
load():Reading the file data
dump():Writing in the file. It takes two paramater
pickle.dump(data,filepointer)
pickling/Serialization: Writing the Python objects in a file
is called pickling
unpickling/depickling/deserialization: Reading the Python
from the file is called depickilng
Writing Data in binary file
import pickle
x=open('abc.dat','wb')
L=['Ram','Hari','Deepti']
pickle.dump(L,x)
print('Data Written Successfully')
x.close()
#Write a program to write {id:__,name:___,grade:____} type 3
data in a file student.dat.
import pickle
x=open('abc.dat','wb')
L={'id':123,'name':'Ramesh','grade':10}
L1={'id':12,'name':'Ayush','grade':12}
L2={'id':13,'name':'Ansh','grade':12}
pickle.dump(L,x)
pickle.dump(L1,x)
pickle.dump(L2,x)
print('Data Written Successfully')
x.close()
or
x=open('abc.dat','wb')
L={}
for i range(3):
L={}
x=input('Id')
y=input("Name")
z=input('Grade')
L['id']=x
L['name']=y
L['grade']=z
pickle.dump(L,x)
print('Data Written Successfully')
x.close()
Reading data from the Binary File
load()
Exception: Runtime errors are called exception.
try:
code that might contains error.
except:
action required
finally:
code that should be executed whether error occured or
not.
or
#with variable as function
'''
'''
import pickle
x=open('abc.dat','rb')
d={}
try:
while (True):
d=pickle.load(x)
print(d)
except:
print('Data Read Successfully')
#WAP to read data from abc.dat and count the total records in
it:
import pickle
x=open('abc.dat','rb')
d={}
c=0
try:
while (True):
d=pickle.load(x)
print(d)
c=c+1
except:
print('Data Read Successfully')
print('Total Records=',c)
#WAP to read data from abc.dat and count the total students
of grade 12:
import pickle
x=open('abc.dat','rb')
d={}
c=0
try:
while (True):
d=pickle.load(x)
print(d)
if d['grade']==12:
c=c+1
except:
print('Data Read Successfully')
print('Total Records=',c)
#Consider a
stu={id:______,name:_________,fees:_______,cls:____}
#WAP to read data from student.dat and count the total fees
paid by student.
import pickle
x=open('student.dat','rb')
c=0
try:
while True:
d=pickle.load(x)
print(d)
c=c+d['fees']
except:
print('Total Fees',c)
x.close()
#WAP to search the student whose name is Amit in student.dat
file.
import pickle
x=open('student.dat','rb')
c=0
try:
while True:
d=pickle.load(x)
if d['name']=='Amit':
print('Record is present')
c=1
except:
if c==0:
print('Record is not present')
x.close()
#WAP to display those those records whose cls is 12.
#State=['wb','up','mp','ma'] .WAP to state.dat file and
display those states that
#starts with M or m.
#Product={sno:___,cat:___,name:___,price:___}
#Write a program to display the name of those products whose
price lies between 100 and 1000.
#WAP to display those produts whose category is 'Daily Care'.
#Working with CSV (Comma Seperated Values)
CSV files are those files which are stored in comma seperated
values.
It is used to create spreadsheets types of files.Data is
stored in the form of rows and cols.
module: import csv
csv is inbuilt module in Python.
file format: filename.csv
specifier: r, w,r+,w+,a,a+
x= open('filename.csv','r')
x will points to the filename.csv for reading.
functions:
writing:
L=[1200,45,78,90]
writerow : It writes one row (list) at a time.
writerows: It writes multiple rows(nested list)
reader(): read. It convert the csv data in the format
supported in Python
writer():write. It converts the Python object in the format
supported by CSV.
Sample program for writing data:
import csv
x=open('student.csv','w')
L=['Ravi',12,23000,'Rjpm']
c=csv.writer(x)
c.writerow(L)
print('Data written successfully')
x.close()
#Multple rows:
import csv
x=open('stud.csv','w',newline='')
L=[12,34,555,66]
L1=[34,67,44,66]
L2=[1,23,3,4]
L3=[L1,L2,L2]
c=csv.writer(x)
c.writerows((L,L1,L2))
c.writerows(L3)
x.close()
#x=open('Stud.csv','w',newline='')
#\n :delimiter
#Reading data From CSV file
import csv
x=open('stud.csv','r',newline='')
c=csv.reader(x)
for i in c:
print(i)
x.close()
emp.csv=[name,class,rollno,city,dept]
WAP to display those records whose city is lucknow.
import csv
x=open('stud.csv','r',newline='')
c=csv.reader(x)
for i in c:
if i[3]=='Lucknow':
print(i)
x.close()
WAP to count total records in emp.csv file.
import csv
x=open('stud.csv','r',newline='')
s=0
c=csv.reader(x)
for i in c:
s=s+1
print('Total Records',s)
x.close()
WAP to count the total employee whose dept is sales
import csv
x=open('stud.csv','r',newline='')
s=0
c=csv.reader(x)
for i in c:
if i[-1]=='Sales':
print(i)
s=s+1
print('Total Records of Sales',s)
x.close()
A csv file “STUDENT.CSV” has structure (admission_number,
Name, Percentage).
Write a function countrec() in Python that would read
contents of the file “STUDENT.CSV”
and display the details of those students whose percentage is
above 75.
Also display number of students scoring above 75%
if i[-1]>75:
WAP to diplay those students whose name starts with D or K.
And also count them.
if i[1][0]=='D' or i[1][0]=='K':
WAP to display those records whose name has exactly five
characters.
if len(i[1])==5:
WAP to read data from student.csv and write also those
records whose class is 12 in XII.csv.
Random Access In File
tell(): It is used to return the cursor position in a file.
seek(): It is used to move the file pointer in a file. It
takes
two paramter
i. offset: No of bytes
ii. position: from where 0: beginning 1. Currrent position 2.
End of file
seek(10,0)
seek(5,1)
seek(-10,2)
The +ve offset values moves the pointer in forward direction
The -ve offset value move the pointer in backward direction
Write a statement to move 10 bytes backward from current
location.
seek(-10,1)
x=open('data.txt','r')
s="WAP to read data from student.csv and write also those
records whose class i"
p=x.read(5)
print(p)
q=x.tell()
print(q)
x.seek(10,2)
p=x.read(5)
print(p)
data.txt="Ram Kumar Verma"
r=open('Data.txt','r')
r.seek(-3,2)
x=r.read(2)
print(x) #rm
r.seek(2,0)
x=r.read(5)
print(x) #m Kum
r.seek(3,1)
x=r.read(2)
print(x) #Ve
WAP to read the data from students.dat and update the name to
XYZ.
'''
'''
import pickle
x=open('abc.dat','rb+')
try:
while True:
k=x.tell()
d=pickle.load(x)
if d['name']=='Ayush':
d['name']='Ayush Verma'
x.seek(k,0)
pickle.dump(d,x)
print(d)
except:
print()
x.close()
import pickle
x=open('abc.dat','rb+')
y=open('temp.dat','wb')
try:
while True:
#k=x.tell()
d=pickle.load(x)
if d['name']=='Ayush':
d['name']='Ayush Verma'
pickle.dump(d,y)
print(d)
except:
print()
x.close()
y.close()
Consider a file Emp={id:___,name:____,sal:____,desig:____}
i. WAP to update the salary of all employees by 10%.
ii. WAP to update the sal of manager by 20 %.
iii. WAP to delete all employees belonging to IT .
import pickle
import os
x=open('abc.dat','rb+')
y=open('temp.dat','wb')
try:
while True:
d=pickle.load(x)
if d['desig']=='IT':
print(deleted Record,d)
else:
pickle.dump(d,y)
except:
print()
x.close()
y.close()
os.remove('abc.dat')
os.rename('temp.dat','abc.dat')
os module:
rename:
os.rename(oldname,newname)
remove():
It deletes the file
Absolute path and relative path:
Abosolute path requires a fully qualified URL. and relative
path require
only file name and rest path will be obtained by py file.
x=open('student.dat','wb')
x=open('C:\\Users\\Raj\\Desktop\\student.dat','wb')
x=open(r'C:\Users\Raj\Desktop\student.dat','wb')
Binary File:
module: pickle - load ()-read,dump-write
#open- dat ,rb,wb,ab
'''