h files exam

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

1-12-24 Chapterwise Test -file Handling Marks:60 Time:2 hours

1. Define a function SGcounter() that counts and display number of Sand Gpresent in a text file 'A.txt
eg., SAGAR JOON IS GOING TO MARKET.
It will display S:2 G:2
def Shctunten):
52/60
feohen ("At x+'");S- 0;(z0
R=f.nigd0
foh in R:
if .ujgoer)=='s'!
S+1

Ehint(1s:)s," Ga:"6)
4.cIoSeLin Python that counts the number of "is", "am" or "are" words present in a text file
2. Writeafunction
"HELLO.TXT". If the "HELLO.TXT" contents are as follows:

Here ore two sentences that contain "is,""am," or "are"


"She is studying for her final exams.
We are planning a triptothe mountains next weekend."
The output of the function should be: Count of is/am/are in file: 2
def funl0:
fzpen('HELLO.tx+", "»";c=0
fon in R:
if a in (is", "am') 'one:
phint=====
("Couwnt0.5 of is/omlore:! c)
f.clse)
3. Write a method in python to read lines from atext file HELLO.TXT to find and display the
occurrence
of the word "hello".
def method ):
f:ipen (" HELLOt , ' ;(-0
R-f.hed0), Spit0
fon xin R:
if Z.upoeh ()=='0.5HELLO':
pnint ('Nwrhon f o uhancesc)
f.clese)
4. Wite auser defined fundtion named Count() that willread the contents of atext filo named
"Indiatxt" and count the number of lines which start with elther "" or "1"
Lg. In the followingparagraph, there are 2lines startng with "" or "T";
"The lndian economy is one of the largest and fastest growing In the world, characterized by a diverse
range of industrles including agriculture, manutacturing, servlces, and informattontechnology. It
boasts asizable consumer base and adynamic entrepreneurlal spirit. However, it alo faces challengos
such as income inequality, poverty, and intrastructure gaps, which the government continually
addresses through pollcy reformsand Initiatives to foster sustainable growth and development."
def couut 0:
fsoer(" Tdio txt'" n");(- 0
R:f.nodlines)
fon in R:
if x ol ih (T):

Phint("Numibon
f.closet)
of Ines slaling

5.Write a method in python toread lines from a text file AZAD.TXT and display those lines, which are
starting with an alphabet T'. 3x5=15

dof fun():
R=foneodlines()
if o]=:'T":
bhint («)
6Shreyas is a programmer, who has recently been given atask to write auser defined function named
write_bin()to create a binary file called Cust file.dat containing customer information customer
number (c_no), name (c_name), quantity (qty), price (price) and amount (amt) of each customer. 4

import pickle
def write bin () :
bin file #Statement 1
while True:
c no=int (input ("enter customer number"))
c name=input ("enter customer name")
qtyint (input ("enter qty"))
price=int (input ("enter price") )
if #Statement 2
print ("Quantity less than 10. .Cannot SAVE")
else:
amt-price * qty
c detail= (c no,c name, qty, price,amt]
#Statement 3
ans=input ("Do you wish to enter more records y/n")
if ans.lower () =='n':
#Statement 4
#Statement 5
#Statement 6

The functión accepts customer number, name, quantity and price. Thereafter, it displays the message
Quantity less than 10... Cannot SAVE', if quantity entered is less than 10. Otherwise the function
calculates amount as price quantity and then writes the record in the form of a list into the binaryfile.

i) Write the correct statement to open a file 'Cust_file.dat' for writing the data of the customer.
chen ("Custiledot""wb")
(i) Which statement should Shreyas fill in Statement 2to check whether quantity is less than 10.
aty<i0:
(ii)Which statement should Shreyas fill in Statement 3 to write data to the binary file and in
Statement 4 to stop further proçessing if the user does not wish to enter more records.
Stade mend 3: PiCKlR,dumb(C-detail, bin-file)
Stokment4: bneak
(iv) What should Shreyas fill in Statement 5 to close the binary file named Cust_file.dat and in
Statement 6 to call a function to write data in binary file?
StalemantS: bin-file.closeC)
Stotemetbi white_binl)
7.

A binary file "PLANTS.dat" has structure (|D, NAME, PRICE).


the user and
a)Write the definition of afunction WRITEREC () in Python, to input data for records from
write them to the file PLANTS.dat.

b)Write the definition of a function SHOWHIGH () in Python,which reads the records of PLANTS.
dat and displays those records for which the PRICE is more than 500.

c) Writethe definitionof a function UPDATE_PRICE () in Pythonwhich updates the price of aplant


whose id is entered by the user. 15
TTE REC():
f:bonile
ojen("PLANTS
Tue:
dat', "wb)
NANE =input("Enten NAME:"
RICE =float(inb ut(Ertos PRI(E:")
L=iD, NAME,PRICE)
þickle.dunb)
chz inpu 'Ajd mere Yln?)
if ch in'Nn:
oreak
fdose ()
de sHowHIGH):
f= opa ("PLANTS.dot'"Hb)
R=þickle. lood (E)
fon tin R:
if ]>500:
phint()
fdosel)
def UPDATE_PRICE 0
f:o þen ("PLANTS. Jal" "bt ")
1D= tinpt("Enen 1o: )
R- þickle lood f)
:sdflat(input('Eritn þaice:"))
foh Kin R: x didnt study 3.5

K] X
pitkbedung
f.flushl)
fclosel)
8 Suppose content of 'Myfile.txt' is: 1
Honesty is the best policy.
What willbe the output of the following code?
myfile =open("Myfile.txt")
x=myfile.read() olp’ 27
print(len(x)
myfile.close()
9 Suppose content of 'Myfile.txt' is 1
Culture is the widening of the mind and of the spirit.
What willbe the output of the following code?
myfile = open("Myfile.txt")
x= myfile.read()
y= x.count('the')
print(y) olp 3
myfile.close)

10 Raghav is trying to write a tuple tup1 =(1,2,3,4,5) on a binary file test.bin. Consider the following
code written by him. 1
import pickle
tupl = (1,2,3,4,5)
myfile = open("test.bin",'wb')
pickle. #Statement 1 myfile.close() dumytut,mgile)
Write the missing code in Statement 1
11.

Winte Sumer
Spriog

Tart Tart

Write relative path and absolute path of strawberries if the 2


current working directory is: C:(Winter\Tart
x1
Relstiu Poth: \Sthawbenies
Abresd. fat: Ci\Sbniy Sueet\ Sthaw behea
12 Assume the content of text file, 'student.txt' is: 1
Arjun Kumar
Ismail Khan
Joseph B
Hanika Kiran
What willbe the data type of data_rec?
myfile = open("Myfile.txt")
data_rec = myfile.readlines()
myfile.close()
a) string b) Mist c) tuple d) dictionary

13 Write a statement to send the file pointer position 10bytes forward from current location of file,
consider fp as file object. 1

a) fp.seek(10)b/fp.seek(10,1) c) fp.tell(10) d) fp.seek(1,10)


14 Which of the following mode in file opening statement results or generates an error if the file does
not exist? 1
a) a+ b)r+ c) w+ d) None of the above

15 Howmany lines does the file myfile00.txt has after the code is executed? 1
>>> mylist=['Iindia', \nis, \nmy', \ncountry, \nand', "\nl',\nam", \na',nproud', \ncitizen']
>>> spc=open("'myfile00.txt","w")
>>> spc.writelines(mylist)
a). 2b). 10c). 9 d). 1
16Write the definition of a function Change.Gender() in Python, which reads the contents of a text
file "BIOPIC. TXT" and displays the content of the file with every occurrence of the word 'he
replaced by 'she. For example, if the content of the file "BIOPIC. TXT" is as follows:
Lost time he went to Agra, there was too much crowd, which he did not like. So this time he decided to
visit some hill station.
The function should read the file content and display the output as follows:
Last time she went to Agra, there was too much crowd, which she did not like. So this time she
decided to visit some hillstation. 3

def ChangeGendeal0:
f: ohen("6IoPIG.TMT"+") ()
I.ubhen=='NE!
R:f. heod(split() x1.5 R='She'!
fon Kinr:
þmint (h,ende )
17

Given a csv file


14

student.csv

File Edit View

Roll No, Name ,Age, Gender


1,Aarav, 10, Male
2,Arya, 3, Male
3,Zenil, 1, Male
4,Zenith, 1, Male
Write a program with UDFS to
a)create csvfile as shown above
imbont (SV
des wnie0: White.whithow (E'Ze wil1,"Male"]
I wfiten. Whit
f:0pon ("sHudot.csv"Mw") phint ('Cheated)sow
(zenith1, 'Wale]
wniten SV. wbitelt)
Whitehwhitetow(Rol! NoNome'","Age'"Gendea"|)
buniter. whitehowlc, "Aahav 10,"Male)
whiteh.writohow/C,"A Mya 3, "Male'J)
b)Search all students whose age between 1 and 3
imboht CSV
def soghch0:
f open('Studant.cs"h) |f.Closet)
ladoh= (sV.headehf)
fon in eoder:
x1

phint()
c)Count the total number of students
te impot csv
dec cout 0:
t: obun("Studort. (sv "a") 1
phintlo
hoodeAz (5V. reoden r);c=-0, falocel)

hext(heoden)
Ct=|

You might also like