Python Lab Programs-1
Python Lab Programs-1
1. f=open("sample.txt","r")
print(word,end="#")
f.close()
OUTPUT:
H#e#l#l#o#,###W#o#r#l#d#!#
2. def count():
f=open("sample.txt","r")
count=f.read()
print(count)
v=0
cons=0
a=0
b=0
for ch in count:
if ch.islower():
a+=1
elif ch.isupper():
b+=1
ch=ch.lower()
if(ch in['a','e','i','o','u']):
v+=1
else:
cons+=1
f.close()
print("vowels are",v)
print("consonants are",cons)
print("lc",a)
print("uc",b)
count()
OUTPUT:
Hello, World!
vowels are 3
consonants are 10
lc 8
uc 2
3.Remove all the lines that contain the character ‘a’ in a file and write it to another file.
f=open("hp.txt","w")
f.write("Harry potter\n Their is a difference in all Harry Potter\n We can see it as harry
groups\nThe books were written by J.K.Rowling")
f.close()
f1=open("hp.txt","r")
f2=open("write.txt","w")
l=f1.readlines()
for i in l:
if 'a' not in i:
f2.write(i)
f2.close()
f1.close()
f1=open("write.txt","r")
content=f1.read()
print(content)
OUTPUT:
The books were written by J.K.Rowling
4.Create a binary file with name and roll number. Search for a given roll number and display the
name. If not found display apporiate message
import pickle
f=open("studetails.dat","ab")
pickle.dump(["shak",1],f)
pickle.dump(["ram",2],f)
pickle.dump(["krishna",3],f)
pickle.dump(["ankit",4],f)
f.close()
f=open("studetails.dat","rb")
flag=False
while True:
try:
x=pickle.load(f)
if x[1]==n:
print("name",x[0])
flag=True
break
except EOFError:
break
if flag==False:
OUTPUT:
enter the roll number3
name krishna
5.Write a random number generator that generates random numbers between 1 and 6(simulates a
dice)
import random
x='y'
while x=='y':
no=random.randint(1,6)
if no==1:
print("--------")
print("[ ]")
print("[1]")
print("[ ]")
print("--------")
if no==2:
print("--------")
print("[ ]")
print("[2]")
print("[ ]")
print("--------")
if no==3:
print("--------")
print("[ ]")
print("[3]")
print("[ ]")
print("--------")
if no==4:
print("--------")
print("[ ]")
print("[4]")
print("[ ]")
print("--------")
if no==5:
print("--------")
print("[ ]")
print("[5]")
print("[ ]")
print("--------")
if no==6:
print("--------")
print("[ ]")
print("[6]")
print("[ ]")
print("--------")
print("\n")
OUTPUT:
--------
[ ]
[4]
[ ]
--------
--------
[ ]
[6]
[ ]
--------