0% found this document useful (0 votes)
109 views19 pages

Grade XII - Python Programs - To Be Written in Record

The document contains code snippets and output related to various file handling operations in Python like: 1. Reading text files and splitting the contents into words or counting characters. 2. Writing to text and binary files, searching, updating and displaying contents. 3. Implementing stack operations like push, pop and display on lists. 4. Random number generation and various string operations using stacks. The code shows how to open, read, write and close files, manipulate file contents using string/list methods, pickle module for binary files and random module. Output verifies successful execution of the programs.

Uploaded by

KHOUSHIK
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)
109 views19 pages

Grade XII - Python Programs - To Be Written in Record

The document contains code snippets and output related to various file handling operations in Python like: 1. Reading text files and splitting the contents into words or counting characters. 2. Writing to text and binary files, searching, updating and displaying contents. 3. Implementing stack operations like push, pop and display on lists. 4. Random number generation and various string operations using stacks. The code shows how to open, read, write and close files, manipulate file contents using string/list methods, pickle module for binary files and random module. Output verifies successful execution of the programs.

Uploaded by

KHOUSHIK
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/ 19

Text File 1 Display each word separated by a #

Program
file=open("SAMPLETEXT.txt","r")
lines=file.readlines()
for line in lines:
words=line.split()
for word in words:
print(word+"#",end="")
print("")
file.close()

Sample Text File

Output
Like#a#joy#on#the#heart#of#a#sorrow,#
Sunset#hangs#on#a#cloud.#
A#golden#storm#of#glittering#sheaves.#
Of#fair#and#frail#and#fluttering#leaves#
The#wild#wind#blows#in#a#cloud.#

TEXT FILE 2 Display number of vowels, consonants, uppercase, lowercase


and consonants
Program
file=open("SAMPLETEXT.txt","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if (ch in ['a','e','i','o','u']):
vowels+=1
elif(ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels are:",vowels)
print("Consonants are:",consonants)
print("Lowercase letters: ",lower_case_letters)
print("Uppercase letters: ",upper_case_letters)

1
Sample Text File:

Output:
Vowels are: 51
Consonants are: 83
Lowercase letters: 129
Uppercase letters: 5

Text File 3 To write contents from one file to a new file and display it.
Program
file=open("FORMAT.txt","r")
lines=file.readlines()
file.close()
file=open("FORMAT.txt","w")
file1=open("SECOND.txt","w")
for line in lines:
if 'a' in line or 'A' in line:
file1.write(line)
else:
file.write(line)
print("All lines that contains 'a' character has been removed in FORMAT.txt file")
print("All lines that contains 'a' character has been saved in SECOND.txt file")
file1.close()
file.close()
Output:
All lines that contain 'a' character has been removed in FORMAT.txt file
All lines that contain 'a' character has been saved in SECOND.txt file
Sample Text File

Output files

2
Binary File 1 To create a binary file, search and display the contents.
Program
import pickle
stud_data={}
list_of_students=[]
no_of_students=int(input("Enter the no.of students:"))
for i in range(no_of_students):
stud_data["roll_no"]=int(input("Enter the roll no.:"))
stud_data["name"]=input("Enter the name:")
list_of_students.append(stud_data)
stud_data={}
file=open("Student.dat","wb")
pickle.dump(list_of_students,file)
print("Data added successfully")
file.close()
import pickle
file=open("Student.dat","rb")
list_of_students=pickle.load(file)
roll_no=int(input("Enter roll no. of students to search:"))
found=False
for stud_data in list_of_students:
if(stud_data["roll_no"]==roll_no):
found=True
print(stud_data["name"],"found in file.")
if(found==False):
print("No student data found. Please try again")
file.close()

Output
Enter the no.of students:2
Enter the roll no.:1
Enter the name:Ram
Enter the roll no.:2
Enter the name:Tom
Data added successfully
Enter roll no. of students to search:2
Tom found in file.

3
Binary File 2 Create a Binary file, Search, Update and Display
Program
import pickle
no_of_students=int(input("Enter the no of students:"))
file=open("Student.dat","wb")
student_data={}
for i in range(no_of_students):
student_data["Roll_No"]=int(input("Enter roll no.:"))
student_data["Name"]=input("Enter Student Name:")
student_data["Marks"]=float(input("Enter Students Mark:"))
pickle.dump(student_data,file)
print(student_data)
file.close()
print("Data inserted successfully")
found=False
roll_no=int(input("Enter the roll no. to search:"))
file=open("Student.dat","rb+")
try:
while True:
pos=file.tell()
student_data=pickle.load(file)
for stud in student_data:
if stud=="Roll_No":
if student_data[stud]==roll_no:
student_data['Marks']=float(input("Enter the marks to update:"))
file.seek(pos)
pickle.dump(student_data,file)
found=True
except EOFError:
if found==False:
print("Roll no not found. please try again")
else:
print("Students marks updated successfully")
file.close()

student_data={}
file=open("Student.dat","rb")
try:
while True:
student_data=pickle.load(file)
print(student_data)
except EOFError:
file.close()

4
Output
Enter the no of students:2
Enter roll no.:1
Enter Student Name: Tom
Enter Students Mark:75
{'Roll_No': 1, 'Name': 'Tom', 'Marks': 75.0}
Enter roll no.:2
Enter Student Name:Ram
Enter Students Mark:64
{'Roll_No': 2, 'Name': 'Ram', 'Marks': 64.0}
Data inserted successfully
Enter the roll no. to search:2
Enter the marks to update:71
Students’ marks updated successfully
{'Roll_No': 1, 'Name': 'Tom', 'Marks': 75.0}
{'Roll_No': 2, 'Name': 'Ram', 'Marks': 71.0}

Random Number Generation


Program
import random
while True:
choice=input("Enter (r) for roll dice or press any other key to quit: ")
if choice!="r":
break
else:
n=random.randint(1,6)
print(n)

Output
Enter (r) for roll dice or press any other key to quit: r
4
Enter (r) for roll dice or press any other key to quit: n

5
Stack Implementation - I
Program
def push():
a=int(input("Enter the element which you want to push: "))
stack.append(a)
return a
def pop():
if stack==[]:
print("Stack empty.... Underflow case ... Can not delete the element.")
else:
print("Deleted element is : ",stack.pop())
def display():
if stack==[]:
print("Stack empty ... no elements in stack. ")
else:
for i in range(len(stack)-1,-1,-1):
print(stack[i])
stack=[]
print("STACK OPERATIONS")
choice='y'
while choice=='y':
print('''1. PUSH 2. POP 3. DISPLAY ELEMENTS IN A STACK *******************''')
c=int(input("Enter your choice: "))
if c == 1:
push()
elif c==2:
pop()
elif c==3:
display()
else:
print("Wrong input.")
choice=input("Do you want to continue or not(y/n): ")

6
Output
STACK OPERATIONS
****************************
1. PUSH
2. POP
3. DISPLAY ELEMENTS IN A STACK
****************************
Enter your choice: 1
Enter the element which you want to push: 2
Do you want to continue or not(y/n): y
1. PUSH
2. POP
3. DISPLAY ELEMENTS IN A STACK
****************************
Enter your choice: 1
Enter the element which you want to push: 3
Do you want to continue or not(y/n): y
1. PUSH
2. POP
3. DISPLAY ELEMENTS IN A STACK
****************************
Enter your choice: 3
3
2
Do you want to continue or not(y/n): y
1. PUSH
2. POP
3. DISPLAY ELEMENTS IN A STACK
****************************
Enter your choice: 2
Deleted element is : 3
Do you want to continue or not(y/n): n

7
Stack Implementation – II
Program
def Spush(s):
for i in s:
stack.append(i)
def Spop():
r=""
for i in range(len(stack)):
ch=stack.pop()
r=r+ch
return r
stack=[]
original_str=input("Enter a string: ")
print("The given original string is: ",original_str)
Spush(original_str)
reversed_str=Spop()
print("The reversed string: ",reversed_str)

Output
Enter a string: abcdef
The given original string is: abcdef
The reversed string: fedcba

Stack Implementation – III

Program
def Push(Books,N):
for i in range(N):
Bookid=int(input("Enter bookid:"))
Bookname=input("Enter book name:")
Author=input("Enter Author name:")
Price=float(input("Enter the price:"))
data=[Bookid,Bookname,Author,Price]
Books.append(data)
def Pop(Books):
if len(Books)==0:
print("Underflow")
else:
return Books.pop()
n=int(input("Enter the number of books to be stored:"))
Books=[]
print("Adding books to stack")
Push(Books,n)
x=int(input("Enter the number of books to be removed:"))
print("Removing books from the Stack")
for i in range(x):
Pop(Books)
print("Books in stack:")
for i in range(len(Books)-1,-1,-1):
print(Books[i])

8
Output
Enter the number of books to be stored:2
Adding books to stack
Enter bookid:1
Enter book name:AAA
Enter Author name:RAM
Enter the price:50
Enter bookid:2
Enter book name:BBB
Enter Author name:TOM
Enter the price:60
Enter the number of books to be removed:1
Removing books from the Stack
Books in stack:
[1, 'AAA', 'RAM', 50.0]

Text File 4 Count the number of characters


Program
def count_W_H():
file=open("Country.txt","r")
W,H=0,0
content=file.readlines()
for x in content:
if x[0]=="W" or x[0]=="w":
W=W+1
elif x[0]=="H" or x[0]=="h":
H=H+1
file.close()
print("W or w:",W)
print("H or h:",H)
count_W_H()

Output
W or w: 1
H or h: 2

9
Text File 5 Count the number of characters and strings

Program
def displaycount():
a_count=0
the_count=0
f=open("SAMPLETEXT.txt","r")
x=f.read()
z=x.split()
for i in z:
if i in "the" or i in "The":
the_count+=1
for j in x:
if j in "a" or j in "A":
a_count+=1
print("The number of a's:",a_count)
print("The number of the's :",the_count)
f.close()
displaycount()

Output
The number of a's: 13
The number of the's : 3

10
Binary File 3 Binary file to search and display the contents
Program
import pickle
def search_emp():
f=open('employee.dat','wb')
while True:
empid=int(input("Enter empid: "))
empname=input("Enter employee name: ")
salary=float(input("Enter employee's salary: "))
rec=[]
data=[empid,empname,salary]
rec.append(data)
pickle.dump(rec,f)
ch=(input("Want more records? yes??"))
if ch.lower() not in 'yes':
break
f.close()
f=open("employee.dat",'rb')
count=0
try:
print("Employee details whose salary is greater than 95000.")
while True:
data=pickle.load(f)
for s in data:
if s[2]>95000:
count+=1
print("Empid: ",s[0])
print("Employee name: ", s[1])
except EOFError:
f.close()
print("Number of employee records whose salary is greater than 95000 is : ", count)
search_emp()
Output
Enter empid: 122
Enter employee name: abc
Enter employee's salary: 25000
Want more records? yes??y
Enter empid: 123
Enter employee name: pqr
Enter employee's salary: 100000
Want more records? yes??y
Enter empid: 124
Enter employee name: xyz
Enter employee's salary: 150000
Want more records? yes??n
Employee details whose salary is greater than 95000.
Empid: 123
Employee name: pqr
Empid: 124
Employee name: xyz
Number of employee records whose salary is greater than 95000 is : 2

11
CSV File 1 Create a CSV File, Search and Display
Program
import csv
def write():
print("Writing Data into CSV file: ")
print("----------------------------------")
f=open("student.csv",'w',newline='')
swriter = csv.writer(f)
swriter.writerow(["Name","Roll No","Mark"])
rec=[]
while True:
name = input("Enter name: " )
Roll=int(input("Enter roll no : "))
Mark=int(input("Enter mark: "))
data = [name,Roll,Mark]
rec.append(data)
ch=input("Do you want to enter more records(y/n): ")
if ch in 'nN':
break
swriter.writerows(rec)
print("Data written in csv file successfully")
f.close()
def read():
f=open("student.csv",'r')
print("Reading data from csv file")
print("-------------------------------")
sreader=csv.reader(f)
for i in sreader:
print(i)
f.close()
def search():
f=open("student.csv",'r')
print('Searching data from csv file.')
print("--------------------------------------")
found=0
sreader=csv.reader(f)
for i in sreader:
if i[2]=="Mark":
pass
elif float(i[2])>85.0:
print("Student Name: ",i[0])
print("Student Roll Number: ",i[1])
found=1
if found==0:
print("No such record.")
else:
print("Search completed")
f.close()
write()
read()
search()

12
Output
Writing Data into CSV file:
----------------------------------
Enter name: abc
Enter roll no : 1
Enter mark: 90
Do you want to enter more records(y/n): y
Enter name: cdx
Enter roll no : 2
Enter mark: 95
Do you want to enter more records(y/n): n
Data written in csv file successfully
Reading data from csv file
-------------------------------
['Name', 'Roll No', 'Mark']
['abc', '1', '90']
['cdx', '2', '95']
Searching data from csv file.
--------------------------------------
No such record.
Student Name: abc
Student Roll Number: 1
Search completed
Student Name: cdx
Student Roll Number: 2
Search completed

13
CSV File 3 Write, Read and Search Data
Program
import csv
def write():
print("Writing data into csv file: ")
print("-------------------------------")
f=open("user.csv",'w',newline='')
swriter=csv.writer(f)
swriter.writerow(['USER ID','Password'])
rec=[]
while True:
userid=int(input("Enter User ID: "))
pwd=input("Enter password: ")
data=[userid,pwd]
rec.append(data)
ch=input("Do you want to enter more choices (y/n): ")
if ch in 'nN':
break
swriter.writerows(rec)
print("Data write in csv file successfully")
f.close()
def read():
f=open('user.csv','r')
print("Reading data from csv file" )
print("---------------")
sreader=csv.reader(f)
for i in sreader:
print(i)
def search():
while True:
f=open('user.csv','r')
print("Searching data from csv file.")
print("-----------------------------------------")
s=input("Enter the userid: ")
found=0
sreader=csv.reader(f)
for i in sreader:
if i[0]== s:
print("Password: ",i[1])
found=1
break
if found==0:
print("Sorry .......... no password found.")
ch=input("Do you want to enter more (Y/N)? :")
if ch in 'nN':
break
f.close()
write()
read()
search()

14
Output
Writing data into csv file:
-------------------------------
Enter User ID: 123
Enter password: 6434
Do you want to enter more choices (y/n): y
Enter User ID: 334
Enter password: jh87
Do you want to enter more choices (y/n): n
Data write in csv file successfully
Reading data from csv file
---------------
['USER ID', 'Password']
['123', '6434']
['334', 'jh87']
Searching data from csv file.
-----------------------------------------
Enter the userid: 344
Sorry .......... no password found.
Do you want to enter more (Y/N)? :y
Searching data from csv file.
-----------------------------------------
Enter the userid: 334
Password: jh87
Do you want to enter more (Y/N)? :n

Left Shift Operator


Program
def Lshift(Arr,n):
L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
x=[10,20,30,40,12,11]
s=2
Lshift(x,s)

Output
[30, 40, 12, 11, 10, 20]

15
Display Word with Longest Length
Program
def longest_word(a):
max1=len(a[0])
temp=a[0]
for i in a:
if len(i)>max1:
max1=len(i)
temp=i
print("The word with longest length is:",temp,"and length is:",max1)
x=int(input("Enter the number of words to be stored in the list:"))
a=[]
for i in range(0,x):
s=input("Enter a word: ")
a.append(s)
longest_word(a)

Output
Enter the number of words to be stored in the list:4
Enter a word: hello
Enter a word: hi
Enter a word: python programming
Enter a word: welcome
The word with longest length is: python programming and length is: 18

Text File 6 Frequently Occurring Words


Program
fh=open("SAMPLETEXT.txt","r")
dic={}
contents=fh.read().split()
for i in contents:
if i not in dic:
dic[i]=contents.count(i)
values=list(dic.values())
values.sort(reverse=True)
keys=[]
for i in range(len(values)):
for j in dic:
if dic[j]==values[i]:
if j not in keys:
keys.append(j)
n=int(input("Enter how many number of frequently occuring words to be found:"))
for i in range(n):
print("count of "+keys[i]+':',values[i])
fh.close()

16
Sample Text File

Output
Enter how many number of frequently occuring words to be found:2
count of is: 4
count of Python: 2
Text File 7 Read the Text File

Program
def Lineswith5words():
fh=open("SAMPLETEXT.txt","r")
l_lines=fh.readlines()
print(l_lines)
print()
for i in l_lines:
words=i.split()
if len(words)==5:
print(i)
Lineswith5words()
Output
['This is a sample text file.\n', 'The file has the following sentences.\n', 'Python is an
interpreted language.\n', 'It is simple and easy\n', 'Python is used for developing many
commercial applications.']
Python is an interpreted language.
It is simple and easy

17
CSV File 4 Create, Read, Display data from CSV file
Program
import csv
def CreateFile():
fh=open("Student.csv","w",newline="")
csvwriter=csv.writer(fh)
csvwriter.writerow(["RollNumber","StudentName","Marks"])
n=int(input("Enter the number of student records:"))
rec=[]
for i in range(n):
rollno=int(input("Enter the roll numberof the student:"))
name=input("Enter student name:")
marks=int(input("Enter mark of student:"))
data=[rollno,name,marks]
rec.append(data)
csvwriter.writerows(rec)
fh.close()
def ReadStudentDetails():
fh=open("Student.csv","r")
csvreader=csv.reader(fh)
fields=next(csvreader)
for i in csvreader:
print("RollNumber:",i[0])
print("Name:",i[1])
print("Marks:",i[2])
fh.close()
def DisplayMaxMarks():
fh=open("Student.csv","r")
maxmark=0
csvreader=csv.reader(fh)
list1=[]
fields=next(csvreader)
for i in csvreader:
if int(i[2])>maxmark:
maxmark=int(i[2])
list1.append(i)
print("Student who scored maximum mark:")
for x in list1:
if int(x[2])==maxmark:
print("Roll number:",x[0])
print("Name:",x[1])

CreateFile()
ReadStudentDetails()
DisplayMaxMarks()

18
Output
Enter the number of student records:2
Enter the roll numberof the student:1
Enter student name:abc
Enter mark of student:99
Enter the roll numberof the student:2
Enter student name:bcd
Enter mark of student:98
RollNumber: 1
Name: abc
Marks: 99
RollNumber: 2
Name: bcd
Marks: 98
Student who scored maximum mark:
Roll number: 1
Name: abc

Frequency of Elements in a List


Program
def func(l,x):
count=0
for i in range(0,len(l)):
if l[i]==x:
print("Found at:",i+1)
count=count+1
if count==0:
print(x,"not found")
else:
print(x,"has frequency of",count,"in the given list")
a=eval(input("Enter the list to be searched (In list format): "))
b=int(input("Enter the elements to be searched:"))
func(a,b)

Output
Enter the list to be searched (In list format): [1,2,2,3,5,4,9,6,1,2,4]
Enter the elements to be searched:4
Found at: 6
Found at: 11
4 has frequency of 2 in the given list

19

You might also like