0% found this document useful (0 votes)
8 views

STUDENT SUPPORT MATERIAL CLASS XII_CS_File handling

The document provides an overview of file handling in programming, detailing the types of files (text and binary), methods for reading and writing data, and the syntax for opening and closing files. It includes examples of how to manipulate both text and binary files, as well as explanations of file modes and paths. Additionally, it covers the use of the pickle module for binary file handling and provides sample code for various file operations.

Uploaded by

Saradha S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

STUDENT SUPPORT MATERIAL CLASS XII_CS_File handling

The document provides an overview of file handling in programming, detailing the types of files (text and binary), methods for reading and writing data, and the syntax for opening and closing files. It includes examples of how to manipulate both text and binary files, as well as explanations of file modes and paths. Additionally, it covers the use of the pickle module for binary file handling and provides sample code for various file operations.

Uploaded by

Saradha S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Page : 25

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.

Steps to process a FILE


1) Determine the type of file usage :
in this section we determine whether file need to be open or not
Sno Method Syntax Description
1 Read() <filehandle>.read( [n] ) Reads at most n bytes ;If no n is specified,
reads the entire file.
Returns the read bytes in the form of a
string . In [11]:file
1=ope n(“E:\\m ydata\\in fo.txt”)
In [12]:readInfo=file1.read(15)
In [13]:print(readInfo)#prints firt 15
#characters of file
In [14]:type(readInfo)
Out[14]:str
2 Readline( ) <filehandle>.readline([n] Reads a line of input ;if in is specified reads at
) most n bytes.
Returns the read bytes in the form string
ending with in(line)character or returns a
blank string if no more bytes are left for
reading in the file.
In [20]:file1 =
open(“E:\\mydata\\info.txt”) In [20]:
readInfo =file1.readline()
In [22]:print (readInfo)
Page : 26
3 readlines() <filehandle>.readlines() Read all lines and returns them in a list
In [23]:file1 =open(“E:\\mydata\\info
text”) In [24]:readInfo =file1.readlines()
In [25]:print
(readInfo) In
[26]:type (readInfo)
Out[26]:list
2) open the file and assign its references to a file object or file handle
3) Process as required
4) close the file

OPENING AND CLOSING FILES


1) open() function is used to open a file
Syntax: file variable/file handle=open(file_name,acce ss
mode) Example F= open('abc.txt,'w')
this statement opens abc.txt in write mode
Note : if file mode is not mentioned in open function then default file mode i.e 'r' is used,

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

Writing data into files


Sno Name Syntax Description
1 Write() <filehandle>.write(str1) Write string str1 to file
referenced by<filehandle>
2 Writelines() <filehandle>.writelines Writes all strings in list L as lines
(L) to file referenced by <filehandle>

BINARY FILE HANDLING:


1) in binary file data is in unreadable format and to work on binary file we have to
convert the data into readable form for read as well as write operation
2) pickling refers to the process of converting the structure to a byte stream before
writing to a file.while reading the content of the file a reverse process called unpickling
is used to convert the byte stream back to the original strstrstructure
3) we have to import pickle module for binary file handling
4) two main method of pickle modules are‐ dump() and load()
5) Syntax of dump():‐ dump(object, fileobject)
6) Syntax of load():‐load(fileobject)

RELATIVE AND ABSOLUTE P AT H


1) The os module provides functions for working with files and directories ('os' stands for
operating system). os.getcwd returns the name of the current directory
()
print(cwd)#cwd is current working directory
2) A string like cwd that identifies a file is called path. A relative path starts from the current
directory whereas an absolute path starts from the topmost directory in file system.
3) Example of Absolute path:E:\project\myfolder\data.txt

ST AND ARD FILE STRE AM


We have to import module sys for standard I/O
stream the standard stream available in python are :
1) standard input stream(sys.stdin)
2) standard output stream(sys.stdout)
3) standard error stream(sys.stderr)
Page : 28

Q1. What is the difference between 'w' and 'a' m odes?


Q2. BINARY file is unreadable and open and close through a function only so what are the
advantages of using binary file
Q3. Write a statement to open a binary file name sample.dat in read mode and the file
sample.dat is placed in a folder ( name school) existing in c drive
Q4. Which of the following function returns a list datatype
A) d=f.read()
B) d=f.read(10)
C) d=f.readline()
D) d=f.readlines()
Q5, How many file objects would you need to manage the following situations :
(a) To process four files sequentially
(b) To process two sorted files into third file
Q6. When do you think text files should be preferred over binary files?
Page : 29
Page : 30

1.
Page : 31

3
Page : 32

6
Page : 33
Page : 34
Page : 35

1. #Program to find number of He and She in file name poem.txt


f=open("c:\\main\\poem.txt","r")
data=f.read()
data=data.split()
print(data)
c=0
c1=0
for ch in data:
ch=ch.upper()
if ch=="HE" :
c=c+1
elif ch=="SHE":
c1+=1
print("No of She",c1)
print("No of he",c)

2. #function to find number of Vowels in file name poem.txt

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()

3. #to write user given values in file in different lines


f=open("c:\\main\\newfile.bat","w")
s=[]
n=int(input("enter the terms to be written"))

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()

4. #program to copy the content of one file into another


f=open("c:\\main\\poem.txt","r")
f1=open("c:\\main\\poem1.txt","w")
rs=" "
while rs:
rs=f.readline()
print(rs)
f1.write(rs)
f.close()
f1.close()

5. #To search for the occurrence of particular word entered by user


def wordsearch(word):
file=open("c:\\main\\poem.txt","r")
data=file.read()
#data=data.upper()
data=data.split()
c=0

for i in data:

#word=word.upper()
if i==word:
c+=1
print("Word found", c,"times")

w=input("enter word to be searched")


wordsearch(w)

6. #Print those word whose first character starts with T


def startwithT():
Page : 37
file=open("c:\\main\\poem.txt","r")
data=file.read()
data=data.split()
for i in data:
if i[0]=="T":
print(i)
file.close()
startwithT()

7. #counting length without new line character


file=open("c:\\main\\myfile1.txt","r")

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)

2. #Program to read, write and updation in list


import pickle
f=open("c:\\main\\list.dat","wb+")
a=eval(input("enter list elements"))
pickle.dump(a,f)
f.seek(0)

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-

#Enter custname,custcode,city in binary file Read file search custcode


import pickle
f=open("cust.dat","ab+")
ch='Y'
Page : 50
while ch=='Y':
l=[]
ccd=input("enter custcode")
cnm=input("enter custname and")
ccity=input("enter city")
l.append(ccd)
l.append(cnm)
l.append(ccity)
# load list into file
pickle.dump(l,f)
ch=input("do you add= more y/n").upper()
if ch=='Y':
continue
else:
break
# read file set pointer
f.seek(0)
flag=False
# Read file
ccdsearch=input("enter custcode to be search from file")
search=[]
try: #Remove Eof Ranout error
while True:
c=pickle.load(f)
print(c)
c1cd=c[0]
c1nm=c[1]
c1city=c[2]
if ccdsearch.upper()==c1cd:
flag=True
search=c
break
except EOFError: #Remove Eof Ranout error
pass #Remove Eof Ranout error
if flag==True:
print("customer found")
print("customer name is:",search[1])
else:
print("customer not found")

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::

QUESTIONS AND ANSWERE AS PER CBSE SAMPLE PAPER


Q.23
Page : 52

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.

import _____________ # Line 1


def addCsvFile(UserName,PassWord): # to write / add data into the CSV file
f=open(' mydata.csv','________') # Line 2
newFileWriter = csv.writer(f)
newFileWriter.writerow([UserName,PassWord])
f.close() #csv file reading code
def readCsvFile(): # to read data from CSV file
with open('mydata.csv','r') as newFile:
Page : 53
newFileReader = csv._________(newFile) # Line 3
for row in newFileReader:
print (row[0],row[1])
newFile.______________ # Line 4
addCsvFile(“Aman”,”123@456”)
addCsvFile(“Anis”,”aru@nima”)
addCsvFile(“Raju”,”myname@FRD”)
readCsvFile() #Line 5

(a) Give Name of the module he should import in Line 1.


(b) In which mode, Aman should open the file to add data into the file
(c) Fill in the blank in Line 3 to read the data from a csv file.
(d) Fill in the blank in Line 4 to close the file.
(e) Write the output he will obtain while executing Line 5.

(a) Line 1 : csv


(b) Line 2 : a
(c) Line 3 : reader
(d) Line 4 : close()
(e) Line 5 : Aman 123@456
Anis aru@nima
Raju myname@FRD
Priti of class 12 is writing a program to create a CSV file “emp.csv”. She has written the
following code to read the content of file emp.csv and display the employee record whose
name begins from “S‟ also show no. of employee with first letter “S‟ out of total record. As
a programmer, help her to successfully execute the given task.
Consider the following CSV file (emp.csv):

1,Peter,3500
2,Scott,4000
3,Harry,5000
4,Michael,2500
5,Sam,4200

import ________ # Line 1


def SNAMES():
with open(_________) as csvfile: # Line 2
myreader = csv._______(csvfile, delimiter=',') # Line 3
count_rec=0
count_s=0
for row in myreader:
Page : 54
if row[1][0].lower()=='s':
print(row[0],',',row[1],',',row[2])
count_s+=1
count_rec+=1
print("Number of 'S' names are ",count_s,"/",count_rec)
(a) Name the module he should import in Line 1 1
(b) In which mode, Priti should open the file to print data. 1
(c) Fill in the blank in Line 2 to open the file. 1
(d) Fill in the blank in Line3 to read the data from a csv file. 1
(e) Write the output he will obtain while executing the above program. 1
(a) csv 1
(b) read mode 1
(c) 'emp.csv' 1
(d) reader 1
(e) 2,Scott,4000
5,Sam,4200 1
Number of “S” names are 2/5
Sanjay Dalmia of class 12 is writing a program to create a CSV file “contacts.csv” which
will contain Name and Mobile Number for some entries. He has written the following
code. As a programmer, help him to successfully execute the given task.

import # Line 1
def addCsvFile(Name,Mobile): # to write / add data into the CSV file

f=open('contacts.csv',' ') # Line 2


newFileWriter = csv.writer(f)
newFileWriter.writerow([Name,Mobile])
f.close()
#csv file reading code
def readCsvFile(): # to read data from CSV file with
open('contacts.csv','r') as newFile:

newFileReader = csv. (newFile) # Line 3 for row in


newFileReader:

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

d) Fill in the blank in Line 4 to close the file. (1)


close()

a) Write the output he will obtain while executing Line 5. (1)


Arjun 8548587526
Arunima 6585425855
Frieda 8752556320
Page : 56
Page : 57

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:

If the file content is as follows:


Updated information
As simplified by official websites.
The EUCount() function should display the output as:
A or a:4
M or m :2
Write a function in Python that counts the number of “The” or “This” words present in a text file
“MY_TEXT_FILE.TXT”.

Note: (The comparison should be case insensitive)


Ans
def displayMeMy():
um=0
Page : 59
f=open("story.txt","rt")
N=f.read()
M=N.split()
for x in M:
if x=="Me" or x== "My":
print(x)
num=num+1
f.close()
print("Count of Me/My in file:",num)
Or
def count_A_M():
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
elif x[0]=="M" or x[0]=="m":
M=M+1
f.close()
print("A or a: ",A)
print("M or m: ",M)
Note : Using of any correct code giving the same result is also
accepted.
num_words = 0
with open('MY_TEXT_FILE.TXT', 'r') as f:
for line in f:
words = line.split()
for word in words:
if word.upper()== 'THE' or word.upper()== 'THIS' :
num_words+=1
Page : 60
print(num_words)
OR
Write a function VowelCount() in Python, which should read each character of a text file
MY_TEXT_FILE.TXT, should count and display the occurrence of alphabets vowels.

Example:
If the file content is as follows: Updated information

As simplified by official websites.


The VowelCount() function should display the output as:
A or a:4
E or e :4
I or I :8
O or o : 0
U or u: 1

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

print("A or a:", count_a)


Page : 61
print("E or e:", count_e)
print("I or i:", count_i)
print("O or o :", count_o)
print("U or u:", count_u)

or any other correct logic


Page : 62

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.

The output of the function should be: Count of Me/My in file: 4

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.

The AMCount() function should display the output as: A or a: 4 M or m :2


def displayMeMy():
num=0
f=open("story.txt","rt")
N=f.read()
M=N.split()
for x in M:
Page : 63
if x=="Me" or x== "My":
print(x)
num=num+1
f.close()
print("Count of Me/My in file:",num)

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

elif x[0]=="M" or x[0]=="m":


M=M+1
f.close()
print("A or a: ",A)
print("M or m: ",M)
Page : 64
Page : 65

A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].


i. Write a user defined function CreateFile() to input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and return number of books by the given Author are stored in the binary file
“Book.dat”

OR

A binary file “STUDENT.DAT” has structure (admission_number,


Name, Percentage). Write a function countrec() in Python that
would read contents of the file “STUDENT.DAT” and display the
details of those students whose percentage is above 75. Also
display number of students scoring above 75%

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])

A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].

i. Write a user defined function CreateFile() to input data


for a record and add to Book.dat .

ii. Write a function CountRec(Author) in Python which


accepts the Author name as parameter and count and
return number of books by the given Author are stored in
the binary file

“Book.dat”

OR
Page : 68

A binary file “STUDENT.DAT” has structure (admission_number,


Name, Percentage). Write a function countrec() in Python that would
read contents of the file “STUDENT.DAT” and display the details of
those students whose percentage is above 75. Also display number of
students scoring above 75%

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()

(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

You might also like