9 PYTHON PROGRAMS (1)
9 PYTHON PROGRAMS (1)
Marks: 30
Python Programming
Write a python program to remove all the lines that contain the
character “a‟ in a text file and write it to another file.
ANSWER:
file1=open("file1.txt","r")
l1=file1.readlines()
file1.close()
file2=open("filetwo.txt","w")
Q1
file1=open("file1.txt","w")
for line in l1: 08
if "a" in line:
file2.write(line)
else:
file1.write(line)
file1.close()
file2.close()
print("lines containing character 'a' are removed from file1 and added to
file2 successfully")
Q2
SET-2
Write a Python program to create binary file and store the details of a
student.
ANSWER:
import pickle
stu={}
myfile=open('student.dat','wb')
choice='y'
while choice=='y':
rno=int(input("enter roll number:"))
name=input("enter name:")
Class=int(input("enter class(11/12):"))
total=int(input("enter total marks:"))
stu['rollno']=rno
stu['name']=name
stu['class']=Class
stu['marks']=total
pickle.dump(stu,myfile)
choice=input("do you want to add more records?(y/n)...")
myfile.close()
stu={}
fin=open('student.dat','rb')
try:
print("file contents:")
while True:
stu=pickle.load(fin)
print(stu)
except EOFError:
fin.close()
Date: 25/01/2023 SET-3 Max. Marks: 30
Python Programming
Write a Python program to find the occurrence of a given word in a
string which is passed as an argument to function.
ANSWER:
def countWord(str1,word):
s=str1.split()
count=0
for w in s:
if w==word:
Q3 count+=1 08
return count
str1=input("Enter a sentence:")
word=input("Enter word to search:")
count=countWord(str1,word)
if count==0:
print("Word,",word,"not found")
else:
print("No. of occurences of word'",word,"'in the string: ",count)
if opt==1:
Push()
elif opt==2:
Pop()
elif opt==3:
Peek()
elif opt==4:
Disp()
else:
print("Invalid Output")
opt=input("Do you want to perform another stack operation (y/n)?:")
Date: 25/01/2023 SET-9 Max. Marks: 30