Class 12 (083) Computer Science Practical File

               

          Practical File

Practical No.1 
Read a text file line by line and display each word separated by a '#'

Program-

file=open("student.txt","r")
lines=file.readlines()
for a in lines:
    words=a.split()
    for b in words:
        print(b+"#",end="")
    print()
file.close()

Note- Make a student text file and save it in the same location where you have saved your program.
Output-















Practical No.2
Read a text file and display the number of vowels/consonant/uppercase/lowercase characters in the file.


f=open("student.txt","r")
show=f.read()

print("The contents of the file are given below=\n",show)
v,c,upper,lower=0,0,0,0

for ch in show:
    if ch.islower():
        lower+=1
    elif ch.isupper():
        upper+=1
    ch=ch.lower()
    if ch in ['a','e','i','o','u']:
        v+=1
    else:
        c+=1
f.close()
print("Vowels are in the file=",v)
print("Consonants are in the file=",c)
print("Uppercase letters are=",upper)
print("lowercase letters are=",lower)

Note- Make a student text file and save it in the same location where you have saved your program.
Output-















Practical No.3
Remove all the lines that contain the character 'a' in a file and write it to another file.

f=open("student.txt","w")
f.write("This is the main file of a python programming in which")
f.write("We are removing all the lines that contains 'a' ")
f.close()

f=open("student.txt","r")
f1=open("writeup.txt","w")
lines=f.readlines()
for i in lines:
    if "a" in i:
        i=i.replace("a"," ")
        f1.write(i)
f1.close()
f.close()

f=open("student.txt","r")
show=f.readline()
print(show)
f.close()

f1=open("writeup.txt","r")
show1=f1.readline()
print(show1)
f1.close()

Output-













Practical No.4
Create a binary file with name and roll number.  Search for a given roll number and display the name, if not found display the appropriate message.

import pickle
def  Writerecord(sroll,sname):
    with open('StudentRecord1.dat','ab') as Myfile:
        srecord={"SROLL":sroll,"SNAME":sname}        
        pickle.dump(srecord,Myfile)
       
def Readrecord():
    with open ('StudentRecord1.dat','rb') as Myfile:
        print("\n-------DISPALY STUDENTS DETAILS--------")
        print("\nRoll No.",' ','Name','\t',end='')
        print()
        while True:
           try:
               rec=pickle.load(Myfile)
               print(' ',rec['SROLL'],'\t' ,rec['SNAME'])
           except EOFError:
                break
def Input():
    n=int(input("How many records you want to create :"))
    for ctr in range(n):
        sroll=int(input("Enter Roll No: "))
        sname=input("Enter Name: ")
        Writerecord(sroll,sname)
        
def SearchRecord(roll):
    with open ('StudentRecord1.dat','rb') as Myfile:
       while True:
          try:
               rec=pickle.load(Myfile)
               if rec['SROLL']==roll:
                   print("Roll NO:",rec['SROLL'])
                   print("Name:",rec['SNAME'])
          except EOFError:
              print("Further records are not find")
              print("Enter the roll number and Try Again")
              break

def main():
    while True:
        print('\nYour Choices are: ')
        print('1.Insert Records')
        print('2.Dispaly Records') 
        print('3.Search Records (By Roll No)')
        print('0.Exit (Enter 0 to exit)')
        ch=int(input('Enter Your Choice: '))
        if ch==1:
            Input()
        elif ch==2:
            Readrecord()
        elif ch==3:
            r=int(input("Enter a Rollno to be Search: "))
            SearchRecord(r)
        else:
            break
main()

Output-





























































Practical No.5
Create a binary file with roll number, name and marks. Input a roll number and update the marks

import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
    roll = int(input("Enter Roll Number :"))
    name = input("Enter Name :")
    marks = int(input("Enter Marks :"))
    student.append([roll,name,marks])
    ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
    try:
        student = pickle.load(f)
    except EOFError:
        break
ans='y'
while ans.lower()=='y':
    found=False
    r = int(input("Enter Roll number to update :"))
    for s in student:
        if s[0]==r:
            print("## Name is :",s[1], " ##")
            print("## Current Marks is :",s[2]," ##")
            m = int(input("Enter new marks :"))
            s[2]=m
            print("## Record Updated ##")
            found=True
            break
        if not found:
            print("####Sorry! Roll number not found ####")
            ans=input("Update more ?(Y) :")
f.close()

Output-















Practical No.6
Write a random number generator that generates random numbers between 1 to 6(simulates as a dice)

import random
ans='y'
while ans.lower()=='y':
    print("="*55)
    print("****************** Rolling the Dice ******************")
    print("="*55)
    num=random.randint(1,6)
    print(num)
    ans=input("Roll again(Y)?")    
print("Thanks for playing")

Output-



















Practical No.7
Create a csv file by entering user id and password. read and search the password for given user id

import csv
def register():
            with open ("user.csv",mode="a", newline="") as f:
                        writer=csv.writer(f,delimiter=",")
                        user_id=input("Enter your id:")
                        password =input("Enter your password:")
                        password2=input("Please re-enter your password:")
                        if password==password2:
                                    writer.writerow([user_id,password])
                                    print("login successful")
                        else:
                                    print("Please try again")
def login():
            user_id=input("Enter your id: ")
            password=input("Enter your password: ")
            with open("user.csv",mode="r") as f:
                        reader=csv.reader(f,delimiter=",")
                        for row in reader:
                                    if row==[user_id,password]:
                                                print ("you are logged in !")
                                                return True
            print ("Please try again!")
            return False
register()
login()

Output-




















Practical No.8
Program to check whether it is a perfect number or not with the help of function.

def perfect(n):
    sum1=0
    for a in range(1,n):
        if (n%a==0):
            sum1=sum1+a
    if (sum1==n):
        print("number is perfect")
    else:
        print("number is not perfect")
    
num=int(input("Enter the number="))
print(perfect(num))

Output-














Practical No.9
Write a Python program to read an entire text file.

file=open("ictshikshascience.txt","w")
file.write("This is the name of my blog.")
file.write("Where you can learn & download all academic subject based topics")
file.close()
file=open("ictshikshascience.txt","r")
show=file.readline()
print("-----The contents of the file is given below-----\n",show)
print("-----Thank you for Visited my blog-----")
print("---Join & Visit our page ictshikshascience----")
print("'-.-'")


Output-

Write all remaining programs by yourself.

For downloading the full practical file

Link1-Click here to Download

Link2-Click here to Download

Join our WhatsApp and Telegram group for all the upcoming contents and updates.

1. WhatsApp  

2. Telegram