STUDENT SUPPORT MATERIAL CLASS XII_CS_File handling
STUDENT SUPPORT MATERIAL CLASS XII_CS_File handling
FILE HANDLING
A file in itself is a bunch of bytes stored on some storage device like hard disk, thumb
drive etc.
TYPES OF FILE
a. Text File b. Binary File
TEXT FILE
1) A text file stores information in ASCII or unicode characters
2) each line of text is terminated, (delimited) with a special character known as EOL
BINARY FILES
1) A binary file is just a file that contains information in the same format in which the
information is held in memory i.e the file content that is returned to you is raw.
2) There is no delimiter for a line
3) No translation occurs in binary file
4) Binary files are faster and easier for a program to read and write than are text files.
5) Binary files are the best way to store program information.
2) close() : the close( ) method of a file object flushes any unwritten information and
3) close the file object after which no more writing can be done
SYNTAX: fileobject.close()
Example F.close( )
FILES MODE
it defines how the file will be accessed
Text Binary File Description Notes
File Mode
Mode
‘r’ ‘rb’ Read only File must exist already ,otherwise python raises I/O error
‘w’ ‘wb’ Write only *If the file does not exist ,file is created.
*If the file exists, python will truncate existing data and
overwrite in tne file. So this mode must be used with
caution.
‘a’ ‘ab’ append *File is in write only mode.
*if the file exists, the data in the file is retained and new
data being written will be appended to the end.
*if the file does not exist ,python will create a new file.
‘r+’ ‘r+b’ or ‘rb+’ Read and *File must exist otherwise error is raised.
write *Both reading and writing operations can take place.
‘w+’ ‘w+b’ or ‘wb+’ Write and *File is created if doesn’t exist.
read *If the file exists, file is truncated(past data is lost).
*Both reading and writing operations can take place.
‘a+’ ‘a+b’ or Write and *File is created if does not exist.
‘ab+’ read *If file exists, files existing data is retained ; new data is
appended.
*Both reading and writing operations can take place.
Page : 27
TEXT FILE H ANDLING
Methods to re ad data from file s
1.
Page : 31
3
Page : 32
6
Page : 33
Page : 34
Page : 35
def countvowel():
L=["A","E","I","0","U","a","e","i","o","u"]
f=open("c:\\main\\poem.txt","r")
data=f.read()
print(data)
c=0
c1=0
for ch in data:
#ch=ch.upper()
if ch in L:
Page : 36
c=c+1
print("No of vowel",c)
countvowel()
for i in range(n):
Rollno=input("enter Rollno")
s.append(Rollno)
name=input("enter to be written in file")
s.append(name+"\n")
f.writelines(s)
f.close()
for i in data:
#word=word.upper()
if i==word:
c+=1
print("Word found", c,"times")
data=""
while True:
rs=file.readline()
data=data+rs.strip()
print(data)
a=len(data)
print(a)
Page : 38
BINARY FILES:-
1. #program to write, read and search students details in binary files using dictionary
import pickle
def writingb():
file=open("c:\\main\\newbfile.dat","ab")
d={}
a=int(input("enter range"))
for i in range(a):
#d["name"]="Tanuj"
d["Rollno"]=int(input("enter rollno"))
d["name"]=input("enter name")
d["marks"]=int(input("enter marks"))
pickle.dump(d,file)
print("written successfully")
file.close()
def readingb():
file=open("c:\\main\\newbfile.dat","rb")
while True:
data=pickle.load(file)
print(data)
file.close()
def search(n):
f=0
try:
file=open("c:\\main\\newbfile.dat","rb")
while True:
data=pickle.load(file)
if data["Rollno"]==n:
print("Data Found")
print(data)
f=1
break
except EOFError:
pass
if f==0:
print("Not Found")
file.close()
writingb()
Page : 39
readingb()
a=int(input("enter no"))
search(a)
data=pickle.load(f)
print(data)
f.close()
f=open("c:\\main\\list.dat","rb+")
L1=[]
data=pickle.load(f)
f.seek(0)
L1=data
a=input("enter value to be replaced")
a1=input("new value")
for i in range(len(L1)):
if str(L1[i])==a:
L1[i]=a1
print("updated list",L1)
pickle.dump(L1,f)
f.close()
f=open("c:\\main\\list.dat","rb")
data=pickle.load(f)
print("New file",data)
f.close()
Q 1) Write a python program to create binary file dvd.dat and write 10 records in it Dvd
id,dvd name,qty,price Display those dvd details whose dvd price more than 25.
SOURCE CODE:
import pickle
f=open("pl.dat","ab")
ch="Y"
while ch=="Y":
l=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
l.append(pi)
l.append(pnm)
l.append(sp)
Page : 40
l.append(p)
pickle.dump(l,f)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.dat","rb+")
try:
while True:
l=pickle.load(f)
if l[3]>25:
print(l)
except EOFError:
pass
f.close()
OUTPUT:::
Q 2) Write a python program to create binary file stud.dat and write 10 records in it Stud
id,Done on 9 Nov 2020 name,perc,total Display those student details whose perc more
than 50.
SOURCE CODE::
import pickle
f=open("stu.dat","ab")
ch="Y"
while ch=="Y":
l=[]
si=int(input("ENTER STUDENT ID "))
snm=input("ENTER STUDENT NAME")
sp=int(input("ENTER PERCENTAGE "))
Page : 41
m=int(input("ENTER MARKS"))
l.append(si)
l.append(snm)
l.append(sp)
l.append(m)
pickle.dump(l,f)
ch=input("DO WANT TO ENTER MORE RECORDS ?(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("stu.dat","rb+")
try:
while True:
g=pickle.load(f)
if g[2]>50:
print(g)
except EOFError:
pass
f.close()
OUTPUT::
Q3:- Write a python program to create binary file emp.dat and enter 10 records in it empid
empnm desg sal city. Display those employee details whose Name starts with R and ends with
P.
Source Code:-
import pickle
f=open("C:\\Games\\emp.dat","wb+")
ch="Y"
while ch=="Y":
L=[]
empno=int(input("Enter employee number:"))
empnm=input("Enter employee name:")
sal=int(input("Enter employee salary:"))
desg=input("Enter the designation of the employee:")
city=input("Enter the city where the employee lives:")
L.append(empno)
L.append(empnm)
L.append(sal)
Page : 42
L.append(desg)
L.append(city)
print("The content which will be written in the file is",L)
pickle.dump(L,f)
ch=input("Do you want to add more(y,n)=").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("C:\\Games\\emp.dat","rb")
f.seek(0)
try:
while True:
c=pickle.load(f)
a=c[1]
if a[0].upper()=="R" and a[-1].upper()=="P":
print(c)
except EOFError:
pass
f.close()
Output:-
Q.Write a Python program to create binary emp.dat and write 10 records in it.
Structure empid,empname,desg,sal and display no of records in the file.
CODE:-
import pickle
ch='Y'
f=open("emp.dat","wb")
while ch=="Y":
l=[]
empid=input("enter employee id")
ename=input("enter emp name")
desg=input("DESIGNATION?")
sal=input("enter salary")
l.append(empid)
l.append(ename)
l.append(desg)
Page : 43
l.append(sal)
pickle.dump(l,f)
ch=input("WANT TO ADD MORE RECORDS?(Y/N)").upper()
if ch=="Y":
continue
else:
break
f.close()
f.seek(0)
f=open('emp.dat','rb')
c=0
try:
while True:
e=pickle.load(f)
print(e)
c=c+1
print(c)
except EOFError:
pass
f.close()
Output:-
Q:Write a python program to create binary file e mp.dat and write 10 records in it
Emp id,e mp name,desg,sal Display those emp details whose salary more than 50000.
SOURCE CODE:
import pickle
f=open("emp.dat","ab+")
ch="Y"
while ch=="Y":
l=[]
eid=int(input("enteremploye id"))
enm=input("enter employe name")
ed=input("enter employe designation")
esal=int(input("enter employe salary"))
Page : 44
l.append(eid)
l.append(enm)
l.append(ed)
l.append(esal)
pickle.dump(l,f)
ch=input("do you want to add more records?(Y/N)").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("emp.dat","rb+")
try:
while True:
a=pickle.load(f)
if a[3]>50000:
print(a)
except EOFError:
pass
f.close()
OUTPUT:
Q:Write a python program to create binary file player.dat and write 10 records in it Player
id,pl name,sports,city . Display those details who belongs to Surat city
Ans:-
import pickle
f=open("player.dat","ab+")
ch='Y'
while ch=='Y':
l=[]
playerid=input("enter player id")
plnm=input("enter player name")
sports=input("enter the name of sports played by that player:")
Page : 45
city=input("enter the name of player's city")
l.append(playerid)
l.append(plnm)
l.append(sports)
l.append(city)
pickle.dump(l,f)
ch=input("do you want to add more records=more y/n").upper()
if ch=='Y':
continue
else:
break
f.close()
f.seek(0)
f=open("player.dat","rb+")
try:
while True:
p=pickle.load(f)
if p[3]=="surat":
print(p)
except EOFError:
pass
f.close()
OUTPUT:-
-------------------------------------------------------------------------------------
WRITE A PYTHON PROGRAM TO CREATE BINARY FILE stu.dat AND WRITE 10
RECORDS IN IT STUD ID,MANE,PERCENT AGE,TOTAL MARKS. DISPLAY THOSE
STUDENT DETAILS WHOSE STUD ID LESS THAN 20.
code
import pickle
f=open("stu.dat","ab")
ch="Y"
while ch=="Y":
l=[]
Id=int(input("Enter Id "))
Page : 46
nm=input("Enter Name")
perc=int(input("Enter percentage "))
marks=int(input("Enter marks"))
l.append(Id)
l.append(nm)
l.append(perc)
l.append(marks)
pickle.dump(l,f)
ch=input("Do you want to enter more records ?(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("stu.dat","rb+")
try:
while True:
a=pickle.load(f)
if a[0]<20:
print(a)
except EOFError:
pass
f.close()
OUTPUT
Enter Id 12
Enter Name abc
Enter percentage 45
Enter marks200
Do you want to enter more records ?(Y/N): Y
Enter Id 01
Enter Name pqr
Enter percentage 77
Enter marks365
Do you want to enter more records ?(Y/N): Y
Enter Id 234
Enter Name xyz
Enter percentage 95
Enter marks475
Do you want to enter more records ?(Y/N): N
[1, 'gk', 92.6, 457]
[1, 'gk', 92.6, 456]
[1, 'gk', 92.6, 456]
[2, 'gg', 45.0, 245]
Q-Write a python program to create binary file player.dat and write 10 records in it ,Player
id,pl name,sports
Display those player details whose sports is athletic.
SOURCE CODE-
import pickle
f=open(“player.dat”, “ab+”)
ch=’Y'
Page : 47
while ch==’Y':
l=[]
playerid=int(input(“enter player id –“))
playernm=input(“enter playernm-“)
sports=input(“enter sports”)
place=input(“enter place”)
l. append(playerid)
l. append (playernm)
l. append(sports)
l. append(place)
pickle. Dump(l, f)
ch=input(“do you want to add more records(Y/N)”). upper()
if ch==’Y':
continue
else:
break
f. close()
f=open(“player.dat”, “rb+”)
try:
while True
e=pickle.load(f)
if e[2]==”athletic”:
print(e)
except EOFError:
pass
f. close()
OUTPUT-
Question -Write a python program to create binary file player.dat and write 10 records in it
,Player id, pl name,sports
Display those player details whose sports is athletic.
Source Code:-
Page : 48
import pickle
ch='Y'
f=open("player.dat","wb")
while ch=="Y":
l=[]
playid=input("enter player id")
pname=input("enter player name")
sports=input("sport name")
l.append(playid)
l.append(pname)
l.append(sports)
pickle.dump(l,f)
ch=input("WANT TO ADD MORE RECORDS?(Y/N)").upper()
if ch=="Y":
continue
else:
break
f.close()
f.seek(0)
f=open("player.dat","rb")
try:
while True:
e=pickle.load(f)
if e[2].capitalize()=="Athletics":
print(e)
except EOFError:
pass
Output:-
Q-Write a python program to create binary file player.dat and write 10 records in it ,Player
id,pl name,sports Display those player details whose sports is chess.
Page : 49
SOURCE CODE-
import pickle
f=open(“player.dat”, “ab+”)
c=’Y'
while c==’Y':
l=[]
playerid=int(input(“enter player id –“))
playernm=input(“enter playernm-“)
sports=input(“enter sports”)
place=input(“enter place”)
l. append(playerid)
l. append (playernm)
l. append(sports)
l. append(place)
pickle. Dump(l, f)
c=input(“do you want to add more records(Y/N)”). upper()
if c==’Y':
continue
else :
break
f. close()
f=open(“player.dat”, “rb+”)
try:
while True:
s=pickle.load(f)
if s[2]==”chess”:
print(s)
except EOFError:
pass
f. close()
● OUTPUT-
CSV FILE :-
Q)Write a python program to create a csv file dvd.csv and write 10 records in it Dvd
id,dvd name,qty,price. Display those dvd details whose dvd price is more than 25.
SOURCE CODE::
import csv
f=open("pl.csv","w")
cw=csv.writer(f)
ch="Y"
Page : 51
while ch=="Y":
l=[]
pi=int(input("enter dvd id "))
pnm=input("enter dvd name ")
sp=int(input("enter qty "))
p=int(input("enter price(in rupees) "))
l.append(pi)
l.append(pnm)
l.append(sp)
l.append(p)
cw.writerow(l)
ch=input("do you want to enter more rec(Y/N): ").upper()
if ch=="Y":
continue
else:
break
f.close()
f=open("pl.csv","r+")
cw=list(csv.reader(f))
for i in cw:
if l[3]>25:
print(i)
f.close()
OUTPUT::
ANS
Anis of class 12 is writing a program to create a CSV file “mydata.csv” which will contain user name
and password for some entries. He has written the following code. As a programmer, help him to
successfully execute the given task.
1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
import # Line 1
def addCsvFile(Name,Mobile): # to write / add data into the CSV file
print (row[0],row[1])
newFile. # Line 4
addCsvFile(“Arjun”,”8548587526”)
Page : 55
addCsvFile(“Arunima”,”6585425855”)
addCsvFile(“Frieda”,”8752556320”)
readCsvFile() #Line 5
a) Name the module he should import in Line 1. (1)
import csv
b) In which mode, Sanjay should open the file to add data into the file (1)
a or a+
c) Fill in the blank in Line 3 to read the data from a csv file. (1)
reader
ans
Page : 58
Write a function AMCount() in Python, which should read each character of a text file
STORY.TXT, should count and display the occurance of alphabets A and M (including small
cases a and m too). Example:
Example:
If the file content is as follows: Updated information
def VowelCount():
count_a=count_e=count_i=count_o=count_u=0
with open('MY_TEXT_FILE.TXT', 'r') as f:
for line in f:
for letter in line:
if letter.upper()=='A':
count_a+=1
elif letter.upper()=='E':
count_e+=1
elif letter.upper()=='I':
count_i+=1
elif letter.upper()=='O':
count_o+=1
elif letter.upper()=='U':
count_u+=1
Write a function in Python that counts the number of “Me” or “My” words present in a text file
“STORY.TXT”. If the “STORY.TXT” contents are as follows:
My first book was Me and My Family.
It gave me chance to be Known to the world.
OR
Write a function AMCount() in Python, which should read each character of a text file STORY.TXT,
should count and display the occurrences of alphabets A and M (including small cases a and m too).
Example: If the file content is as follows:
Updated information As simplified by official websites.
OR
def AMCount():
f=open("story.txt","r")
A,M=0,0
r=f.read()
for x in r:
if x[0]=="A" or x[0]=="a" :
A=A+1
OR
Ans
import pickle
def createFile():
fobj=open("Book.dat","ab")
BookNo=int(input("Book Number : "))
Book_name=input("Name :")
Author = input("Author:" )
Price = int(input("Price : "))
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,fobj)
fobj.close()
def CountRec(Author):
fobj=open("Book.dat","rb")
num = 0
Page : 66
try:
while True:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num
OR
import pickle
def CountRec():
fobj=open("STUDENT.DAT","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
if rec[2] > 75:
print(rec[0],rec[1],rec[2],sep="\t")
num = num + 1
except:
fobj.close()
return num
40 Write a function SCOUNT( ) to read the content of binary file “NAMES.DAT‟ and
display number of records (each name occupies 20 bytes in file ) where name begins
from “S‟ in it.
For. e.g. if the content of file is:
SACHIN
AMIT
AMAN
SUSHIL
DEEPAK 5
HARI SHANKER
Function should display
Total Names beginning from “S” are 2
OR
Consider the following CSV file (emp.csv):
Sl,name,salary
1,Peter,3500
Page : 67
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200
Write Python function DISPEMP( ) to read the content of file emp.csv and display only
those records where salary is 4000 or above
Ans
def SCOUNT( ):
s=' '
count=0
with open('Names.dat', 'rb') as f:
while(s):
s = f.read(20)
s=s.decode( )
if len(s)!=0:
if s[0].lower()=='s':
count+=1
print('Total names beginning from "S" are ',count)
OR
import csv
def DISPEMP():
with open('emp.csv') as csvfile:
myreader = csv.reader(csvfile,delimiter=',')
print("%10s"%"EMPNO","%20s"%"EMP NAME","%10s"%"SALARY")
for row in myreader:
if int(row[2])>4000:
print("%10s"%row[0],"%20s"%row[1],"%10s"%row[2])
“Book.dat”
OR
Page : 68
import pickle
def createFile():
fobj=open("Book.dat","ab")
Book_name=input("Name :")
Author = input(“Author: “)
rec=[BookNo,Book_Name,Author,Price]
pickle.dump(rec,fobj)
fobj.close()
(ii)
def CountRec(Author):
fobj=open("Book.dat","rb")
num = 0
try:
while True:
rec=pickle.load(fobj)
Page : 69
if Author==rec[2]:
num = num + 1
except:
fobj.close()
return num
OR
import pickle
def CountRec(:
fobj=open("STUDENT.DAT","rb")
num = 0
try
while True:
rec=pickle.load(fobj)
if rec[2] > 75:
print(rec[0],rec[1],rec[2],sep="\t")
num = num + 1
except:
fobj.close()
return num
Page : 70