# Program-05.
Read a text file line by line and display each word
seperated by a ‘#’.
file = open("C:\\Users\\vidhyaashram\\Desktop\\1.txt", 'r')
lines = file.readlines ( )
print(lines)
for line in lines :
words = line.split( )
print(words)
for word in words :
print(word+"#", end =" ")
file.close ( )
['hello everyone\n']
['hello', 'everyone']
hello# everyone#
'''Program-06: 06 Read a text file and display the number the number
of vowels/consonants/
uppercase/lowercase characters in the file.'''
file = open ("C:\\Users\\vidhyaashram\\Desktop\\1.txt", 'r')
content = file.read( )
print(content)
vowels = 0
consonants = 0
lowercase = 0
uppercase = 0
for ch in content :
if (ch.isalpha()):
if (ch.islower( )):
lowercase += 1
elif (ch.isupper()):
uppercase +=1
ch = (ch.lower ( ))
if (ch in ['a', 'e', 'i', 'o', 'u']) :
vowels += 1
else :
consonants += 1
file.close ( )
print ("Vowels are : ", vowels)
print ("Consonants are : ", consonants)
print ("Lowercase are : ", lowercase)
print ("Uppercase are : ", uppercase)
hello everyone
Vowels are : 6
Consonants are : 7
Lowercase are : 13
Uppercase are : 0
'''Program - 7 (a):Create a binary file with name and roll no. Search
for a given roll no. and display
the name, if not found display appropriate message.'''
import pickle
file = open ("stud1.bin", "wb")
dic = { }
n = int (input ("Enter number of students: ") )
for key in range (n):
roll_no = int (input ("Enter roll no") )
name = input ("Enter name: ")
dic [roll_no] = { }
dic [roll_no] ["name"] = name
print(dic)
pickle.dump (dic, file)
file.close ( )
Enter number of students: 2
Enter roll no 1
Enter name: Koushik
Enter roll no 2
Enter name: Abhilash
{1: {'name': 'Koushik'}, 2: {'name': 'Abhilash'}}
'''Program-7 (b) :Read data from binary file '''
import pickle
#opening the dictionary using command line:
file = open ("stud1.bin", "rb")
d = pickle. load (file)
roll_no = int (input ("Enter roll no to search the students name :") )
for key in d :
if key == roll_no :
print ("The name of roll no" , key, "is", d[key])
if (roll_no not in d) :
print ("This roll no doesn’t exist")
break
file. close ( )
Enter roll no to search the students name : 1
The name of roll no 1 is {'name': 'Koushik'}
'''Program-8 (a):Create a binary file with roll. number, name and
marks. Input the roll no. and
update the marks.'''
import pickle
file = open ("stud.bin", "wb+")
dic = { }
n = int (input ("Enter number of students : ") )
for key in range (n) :
roll_no = int (input ("Enter roll no") )
name = input ("Enter name : ")
marks = int (input ("Enter your marks : ") )
dic [roll_no] = { }
dic [roll_no] ["name"] = name
dic [roll_no] ["marks"] = marks
print(dic)
pickle. dump (dic, file)
file. close ( )
Enter number of students : 2
Enter roll no 1
Enter name : Koushik
Enter your marks : 34
Enter roll no 2
Enter name : Abhilash
Enter your marks : 32
{1: {'name': 'Koushik', 'marks': 34}, 2: {'name': 'Abhilash', 'marks':
32}}
'''Program-8(b):Read data from binary file'''
import pickle
file = open ("stud.bin", "rb+")
d = pickle.load(file)
roll_no = int (input ("Enter roll no to update marks") )
for key in d :
if key == roll_no:
m = int (input ("Enter the marks : ") )
d [roll_no] ["marks"] = m
print (d)
if roll_no not in d :
print ("roll no doesn’t exist")
break
pickle.dump(d,file)
file.close ( )
Enter roll no to update marks 1
Enter the marks : 56
{1: {'name': 'Koushik', 'marks': 56}, 2: {'name': 'Abhilash', 'marks':
32}}
'''Program - 9.Remove all the lines that contain the character ‘a’ in
a file and write it to another
file.'''
file = open ("C:\\Users\\vidhyaashram\\Desktop\\fruits1.txt","r")
lines = file.readlines( )
print(lines)
file.close( )
file1 = open ("C:\\Users\\vidhyaashram\\Desktop\\fruits1.txt",'w')
file2 = open ("C:\\Users\\vidhyaashram\\Desktop\\fruits2.txt",'w')
for line in lines:
if 'a' in line or 'A' in line :
file2.write(line)
else :
file1.write(line)
print ("All lines that contains a char has been removed from
fruits1.txt")
print ("All lines that contains a char has been saved in fruits2.txt")
file1.close ( )
file2.close ( )
['kiwi\n', 'Apple\n', 'Banana\n', 'Orange\n']
All lines that contains a char has been removed from fruits1.txt
All lines that contains a char has been saved in fruits2.txt
'''Program - 10:Write a code for a random number generator that
generates random numbers
from 1 - 6 (Similar to a dice)'''
import random
while True :
choice = input ("Enter r to roll dice or press any other key to
quit")
if choice !='r':
break
n=random.randint(1,6)
print(n)
Enter r to roll dice or press any other key to quit r
Enter r to roll dice or press any other key to quit 6
'''Program - 11:Take a sample of 10 phishing emails (or any text file)
and find the most commonly
occurring word'''
file = open ("C:\\Users\\vidhyaashram\\Desktop\\1.txt", 'r')
content=file.read()
max=0
max_occuring_word=""
occurance_dict={}
words=content.split()
for word in words:
count=content.count(word)
occurance_dict.update({word:count})
if(count>max):
max=count
max_occuring_word=word
print("most occuring word is:",max_occuring_word)
print("number of times it occurs:", max)
print("other words frequency:")
print(occurance_dict)
most occuring word is: hi
number of times it occurs: 2
other words frequency:
{'hello': 1, 'everyone': 1, 'hi': 2}
'''Program-12:Write a python program to implement a stack using a list
data structure'''
stack = []
# append() function to push
# element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
# pop() function to pop
# element from stack in
# LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Stack after elements are popped:
[]
'''Program-13 Write a python program to demonstrate .csv file'''
import csv
fh=open("student.csv","w")
stuwriter=csv.writer(fh)
stuwriter.writerow(["rollno","name","marks"])
for i in range(2):
print("student record", (i+1))
rollno=int(input ("enter rollno:"))
name=input("Enter the name:")
marks=float(input("enter marks"))
stu_rec=[rollno, name, marks]
stuwriter.writerow(stu_rec)
fh.close()
student record 1
enter rollno: 1
Enter the name: Koushik
enter marks 34
student record 2
enter rollno: 2
Enter the name: Abhilash
enter marks 35
'''program - 14:Create a CSV file by entering user-id and password,
read and search the password
for given user id'''
import csv
#user -id and password list
List=[["user1", "password1"],
["user2", "password2"],
["user3", "password3"],
["user4", "password4"],
["user5", "password5"]]
#opening the file to write the records
f1=open("userInformation.csv","w",newline="\n")
# Here, you create a CSV writer object called writer associated with
the file f1.
writer=csv.writer(f1)
writer.writerows(List)
f1.close()
#opening the file to read the records
f2=open("userInformation.csv","r")
rows=csv.reader(f2)
userId=input("Enter the user-id:" )
flag = True
for record in rows:
if record[0]== userId:
print("The password is:",record[1])
flag= False
break
if flag:
print("User-id not found")
Enter the user-id:user8
User-id not found
''' Program-21:Write a Program to implement the Stack without using
pre defined Function'''
def isEmpty (stk) :
if stk == []:
return True
else :
return False
def Push (stk, item) :
stk.append(item)
top = len(stk) - 1 # imagine no.of element that i have in stack 5
then 5-1= 4
def Pop(stk) :
if isEmpty(stk) :
return "Underflow"
else :
item = stk.pop()
if len(stk) == 0:
top = None
else:
top = len(stk) - 1
return item
def Peek(stk):
if isEmpty(stk):
return "UnderFlow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("stack empty")
else :
top =len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
#_main_
Stack=[]
top=None
while True :
print("STACK OPERATIONS")
print("1.PUSH")
print("2.POP")
print("3.Peek")
print("4.Display Stack")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item = int(input("Enter item:"))
Push(Stack, item)
elif ch==2:
item = Pop(Stack)
if item =='underflow':
print("Underflow!stack is empty!")
else:
print("popped item is",item)
elif ch==3:
item = Peek(Stack)
if item=='underflow':
print("Underflow! Stack is empty!")
else :
print('topmost item is',item)
elif ch==4:
Display(Stack)
elif ch==5:
break
else:
print("Invalid choice!")
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):1
Enter item:2
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):2
popped item is 2
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):1
Enter item:2
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):1
Enter item:3
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):3
topmost item is 3
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):4
3 <-top
2
STACK OPERATIONS
1.PUSH
2.POP
3.Peek
4.Display Stack
5.Exit
Enter your choice(1-5):5
'''Program-22.Write a python interface program to demonstrate select
query.'''
import mysql.connector as sqltor
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("select * from student")
data=cursor.fetchall()
for row in data:
print(row)
mycon.close()
('2', 'Venki', '33')
('3', 'Vani', '34')
('11', 'Rithes', '17')
'''Program-23.Write a python interface program to demonstrate insert
query.'''
import mysql.connector as sqltor
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("insert into student values(11,'Rithes',17)")
mycon.commit()
print("One Record Inserted Successfully!!")
mycon.close()
One Record Inserted Successfully!!
'''Program-23.Write a python interface program to demonstrate delete
query.'''
import mysql.connector as sqltor
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("delete from student where name = 'ramu'")
mycon.commit()
print("Deleted Successfully")
mycon.close()
Deleted Successfully
'''Program-24.Write a python interface program to demonstrate update
query.'''
import mysql.connector as sqltor
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("update student set name='Venki' where sid=2")
mycon.commit()
print("Updated Successfully")
mycon.close()
Updated Successfully
import mysql.connector as sqltor
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("select * from student")
data=cursor.fetchall()
count=cursor.rowcount
for row in data:
print(row)
mycon.close()
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("insert into student values(10,'ramu',23)")
mycon.commit()
print("One Record Inserted Successfully!!")
mycon.close()
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("delete from student where name = 'Abhi'")
mycon.commit()
print("Deleted Successfully")
mycon.close()
mycon= sqltor.connect(host =
"localhost",user="root",passwd="root",database="koushik")
if mycon.is_connected()== False:
print('Error')
cursor = mycon.cursor()
cursor.execute("update student set name='Vani' where sid=3")
mycon.commit()
print("Updated Successfully")
mycon.close()
('2', 'Ravi', '33')
('3', 'Vani', '34')
('110', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
('10', 'ramu', '23')
One Record Inserted Successfully!!
Deleted Successfully
Updated Successfully