[go: up one dir, main page]

0% found this document useful (0 votes)
13 views7 pages

File Handling - Worksheet - Set 4 - AK

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views7 pages

File Handling - Worksheet - Set 4 - AK

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

FILE HANDLING – SET 4

Consider the file poem.txt which contains following data:


Why?
we work, we try to be better
we work with full zest
but, why is that we just don’t know nay letter
we still give our best
we have to steal
But, why is that we still don’t get a meal.

1.Write a program to read the complete file in a list.


Answer :
with open('poem.txt','r')as fh:
r=fh.readlines()
print(r)

2.Write a program to display size of the file in bytes.


Answer :
with open('poem.txt','r')as fh:
r=fh.read()
size=len(r)
print('size of file=',size)

3.Write a program to display number of lines in the file.


Answer :
with open('poem.txt','r')as fh:
r=fh.readlines()
n=len(r)
print('number of lines=',n)

4.Write a program to count and display lines starting with


letter ‘w’.
Answer :
with open('poem.txt','r')as fh:
c=0
for i in fh.readlines():
if i[0].lower()=='w':
c=c+1
print(i)
print('number of lines starting with w =',c)

5.Write a program to count and display number of words in


the file, also print length of each word.
Answer :
with open('poem.txt','r')as fh:
c=0
l=0
for i in fh.readlines():
for word in i.split():
l=len(word)
c=c+1
print('word=',word,'length=',l)
print('total number of words =',c)

6.Write a program to count and display the occurence of word


‘why’ in the file.
Answer :
with open('poem.txt','r')as fh:
c=0
for i in fh.readlines():
for word in i.split():
if(word.lower()=='why'):
c=c+1
print('total number of why =',c)

7.Write a program to count the words starting with vowel.


Answer :
with open('poem.txt','r')as fh:
c=0
v='aeiouAEIOU'
for i in fh.readlines():
for word in i.split():
if(word[0] in v):
c=c+1
print('total number of words starting wiht vowel =',c)

8.Write a program to display the longest line of the file.


Answer :
with open('poem.txt','r')as fh:
longest=""
r=fh.readlines()
for line in r:
if len(line)>len(longest):
longest=line
print("longest line's length=", len(longest))
print(longest)

9.What will be the output of the following code?

fh=file("poem.txt","r")
size=len(fh.read())
print(fh.read(5))
fh.close()
Answer :
Ans. No output

10.What will be the output of the following code?


fh=open("poem.txt","r")
s1=fh.read(28)
print(s1)
fh.close()
Answer :
Why?
we work, we try t
11. what will be the output of the following code?
fh=open("poem.txt","r")
s1=fh.readline()
s2=fh.readline()
s3=fh.read(15)
print(s3)
fh.close()
Answer :
we work with fu

12.Write a program to copy the contents of the file ‘poem.txt’


to ‘poem1.txt’ barring the lines starting with letter ‘b’.
Answer :
f1=open('poem.txt','r')
f2=open('p3.txt','w')
for i in f1.readlines():
if(i[0].lower()!='b'):
f2.write(i)
f1.close()
f2.close()

13.Write a code to print just the last line of the file ‘poem.txt’.
Answer :
f1=open('poem.txt','r')
r=f1.readlines()
print(r[-1])

14.Write a single loop to display all the contents of file


poem.txt after removing leading and trailing whitespaces.
Answer :
for r in open('poem.txt').readlines():
print(r.strip())

15.A text file contains alphanumeric text say an.txt. write a


program that reads this text file and prints only the numbers
or digits from the file.
Answer :
with open('an.txt','r') as f:
c=f.read()
for i in c:
if i.isdigit():
print(i)

16.Read the code given below and answer the question:


fh=open(“temp.txt”,”w”)
fh.write(“Bye”)
fh.close()
If the file contains “GOOD” before execution, what will be the
contents of the file after execution of this code?
Answer :
Bye

17.What will be the output of the following code?


import pickle
names=['first','second','third','fourth','fifth']
lst=[]
for i in range(-1,-5,-1):
lst.append(names[i])
with open('text.dat','wb') as f:
pickle.dump(lst,f)
with open('text.dat','rb') as f:
nlist= pickle.load(f)
print(nlist)
Answer :
[‘fifth’, ‘fourth’, ‘third’, ‘second’]

18.Your recipe uses some ingredients. write a program to


store the list of ingredients in a binary file.
Answer :
import pickle
with open('ingredients.dat','wb') as f:
lst=[]
n=int(input('enter the number of ingredients: '))
for i in range(n):
ing=input('enter the name of ingredient: ')
lst.append(ing)
print(lst)
pickle.dump(lst,f)

with open('ingredients.dat','rb') as f:
lst=pickle.load(f)
print(lst)

19.Write a program to increase the salary by Rs. 2000/- of


the employee having empno 1251 in the file empl.dat.
Answer :
import pickle
import os
emp={}
found=False
f=open("emp1.dat","rb")
t=open("temp","wb")
try:
emp=pickle.load(f)
while True:
if emp['empno']==1251:
emp['salary']=emp['salary']+2000
found=True
pickle.dump(emp,t)
emp=pickle.load(f)

except EOFError:
if found=False:
print('no match found')
else:
print('record updated successfully')
f.close()
t.close()
os.remove('emp1.dat')
os.rename('temp','emp1.dat')

20.Consider the following definition of dictionary Multiplex,


write a function in python to search and display all the
contents in a pickled file cinema.dat, where Mtype key of the
dictionary is matching with the value ‘Comedy’.
Mutliplex={‘Mno’:……,’Mname’:………, ‘Mtype’:…….}
Answer :
def search_name():
import pickle
z=0
temp={}
f=open("cinema.dat","rb")
try:
while True:
temp=pickle.load(f)
if temp['Mtype'] in 'Comedy':
print(temp)
z=1
except EOFError:
if(z==0):
print("not found")
else:
print("search successful")
f.close()

#calling function
search_details()

You might also like