Sheep
Sheep
SESSION: 2024-2025
SUBMITTED BY:
CLASS: XII - D
1
INDEX
5 Python program to count the number of vowels, consonants, digits and special characters in a string. 12
8 Write a program to read a text file line by line and display each word separated by '#'. 15
Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase characters and other than
9 character and digit in the file. 16
Write a Python code to find the size of the file in bytes, the number of lines, and number of words and no. of
10 character. 17
2
11 Write a method in python to write multiple lines of text contents into a text file mylife.txt. 18
Write a function in Python to read lines from a text file diary.txt, and display only those lines, which are starting
12 with an alphabet 'P'. 19
Write a method in Python to read lines from a text file INDIA.TXT, to find and display the occurrence of the word
13 'India'. 20
Assuming that a text file named first.txt contains some text written into it, write a function that reads the file first.txt
14 and creates a new file named second.txt, to contain only those words from the file first.txt which start with a 21
lowercase vowel (i.e. with 'a', 'e', 'i', 'o', 'u').
15 Write a function in Python to count and display the number of vowels in a text file. 22
i. Write a user defined function insertRec() to input data for a student and add to student.dat.
16 23-24
ii. Write a function searchRollNo( r ) in Python which accepts the student’s rollno as parameter and searches the
record in the file “student.dat” and shows the details of student i.e. rollno, name and marks (if found) otherwise
shows the message as ‘No record found’.
17 i. Write a user defined function CreateEmp() to input data for a record and create a file emp.dat. 25-26
ii. Write a function display() in Python to display the detail of all employees whose salary is more than 50000.
3
A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and add to “Book.dat” .
18 27-28
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and return
number of books by the given Author are stored in the binary file “Book.dat”.
A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage). Write a function countrec()
19 in Python that would read contents of the file “STUDENT.DAT” and display the details of those students whose 29-30
percentage is above 75. Also display number of students scoring above 75%.
A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post, Salary]
(a) Write a user-defined function named NewEmp() to input the details of a new employee from the user and store it
20 in EMP.dat. 31-32
(b) Write a user-defined function named SumSalary(Post) that will accept an argument the post of employees & read
the contents of EMP.dat and calculate the SUM of salary of all employees of that Post.
i. Write a user defined function MakeFile( ) to input multiple items from the user and add to Items.dat
21 33-34
ii. Write a function SearchRec(Code) in Python which will accept the code as parameter and search and display the
details of the corresponding code on screen from Items.dat.
22
23
24
4
25
26
27
28
29
30
31
32
33
34
35
36
5
37
38
39
40
41
42
Teacher’s Signature:
6
#1 Write a program to check a number whether it is palindrome or not.
CODE:
a=int(input("give a number"))
print(f"number 1 is {a} ")
def reverse1():
result=str(a)
return result[::-1]
z =int(reverse1())
print(f"number reversed is {reverse1()}")
if z==a:
print("palindrome")
else: print("not palindrome")
OUTPUT:
7
#2 Write a program to display ASCII code of a character and vice versa.
CODE:
def char_to_ascii(char):
return ord(char)
def ascii_to_char(code):
return chr(code)
character=98
ascii_to_char(character)
OUTPUT:
8
#3 Program to make a simple calculator.
CODE:
def add (a,b):
return a+b
def sub (a,b):
return a-b
def mul (a,b):
return a*b
def div (a,b):
return a/b
def mod (a,b):
return a%b
def power (a,b):
return a**b
def floordiv (a,b):
return a//b
def main():
while True:
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Modulus")
print("6. Power")
print("7. Floor Division")
print('8. Exit')
choice = int(input("Enter your choice: "))
if choice == 8:
break
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
if choice == 1:
print(add(a,b))
elif choice == 2:
print(sub(a,b))
elif choice == 3:
print(mul(a,b))
elif choice == 4:
print(div(a,b))
9
elif choice == 5:
print(mod(a,b))
elif choice == 6:
print(power(a,b))
elif choice == 7:
print(floordiv(a,b))
else:
print("Invalid choice")
main()
OUTPUT:
10
#4 Example of Global and Local variables in function
CODE:
def fun():
global x
x = 10
print(x)
fun()
print(x)
OUTPUT:
11
#5 Python program to count the number of vowels, consonants, digits and special characters in a
string.
CODE:
def countvowels(s):
vowels = 0
consonants = 0
digits = 0
special = 0
for i in s:
if i.isalpha():
if i in 'aeiouAEIOU':
vowels += 1
else:
consonants += 1
elif i.isdigit():
digits += 1
else:
special += 1
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Digits: {digits}")
print(f"Special: {special}")
countvowels("Hello World! 123")
OUTPUT:
12
#6 Python Program to add marks and calculate the grade of a student
CODE:
def grade(marks):
if marks >= 90:
return 'A'
elif marks >= 80:
return 'B'
elif marks >= 70:
return 'C'
elif marks >= 60:
return 'D'
else:
return 'F'
marks = int(input("Enter marks: "))
print(f"Grade: {grade(marks)}")
OUTPUT:
13
#7 Generating a List of numbers Using For Loop.
CODE:
a = []
for i in range(1,11):
a.append(i)
print(a)
OUTPUT:
14
#8 Write a program to read a text file line by line and display each word separated by '#'.
CODE:
file1 = open("testfile.txt", "r")
OUTPUT:
15
#9 Read a text file and display the number of vowels/ consonants/ uppercase/ lowercase
characters and other than character and digit in the file.
CODE:
file1 = open("testfile.txt", 'r')
vowels_count = 0
consonants_count = 0
uppercase_count = 0
lowercase_count = 0
other_count = 0
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
file1.close()
print(f"Vowels: {vowels_count}")
print(f"Consonants: {consonants_count}")
print(f"Uppercase characters: {uppercase_count}")
print(f"Lowercase characters: {lowercase_count}")
print(f"Other characters: {other_count}")
OUTPUT:
16
#10 Write a Python code to find the size of the file in bytes, the number of lines, and number of
words and no. of character.
CODE:
file1 = open('testfile.txt','r')
num_lines = 0
num_words = 0
num_char = 0
def size (a):
a.read()
return a.tell()
for i in file1:
num_lines += 1
for j in i:
num_char += 1
w = i.split()
num_words += len(w)
OUTPUT:
17
#11. Write a method in python to write multiple line of text contents into a text file mylife.txt.
CODE:
file = open('mylife.txt','w')
file.write('ABC\nDEF\nGHI\nJKL')
file = open('mylife.txt','r')
print(file.read())
OUTPUT:
18
#12. Write a function in Python to read lines from a text file diary.txt, and display only those
lines, which are starting with an alphabet 'P'.
If the contents of file is :
I hope you will please write to me from all the cities you visit.
Please accept them with the love and good wishes of your friend.
He never thought something so simple could please him so much.
The output should be:
Please accept them with the love and good wishes of your friend.
CODE:
file = open('diary.txt', 'r')
for i in file:
if i[0] == 'P':
print(i)
OUTPUT:
19
#13. Write a method in Python to read lines from a text file INDIA.TXT, to find and display the
occurrence of the word 'India'. For example, if the content of the file is:
India is the fastest-growing economy. India is looking for more investments around the globe.
The whole world is looking at India as a great market. Most of the Indians can foresee the
heights that India is capable of reaching.
The output should be 4.
CODE:
file = open('INDIA.txt', 'r')
c=0
for i in file:
a = i.split(' ')
for j in a:
if j == 'India':
c+=1
print(c)
OUTPUT:
20
#14. Assuming that a text file named first.txt contains some text written into it write a function
that reads the file first.txt and creates a new file named second.txt, to contain only those words
from the file first.txt which start with a lowercase vowel (i.e. with 'a', 'e', 'i', 'o', 'u').
For example if the file first.txt contains
Carry umbrella and overcoat when it rains
Then the file second.txt shall contain
umbrella and overcoat it
CODE:
def addwordswithvowelstart ():
ffile = open('first.txt','r')
vowels = ['a', 'e', 'i', 'o', 'u']
for line in ffile:
a = line.split()
sfile = open('second.txt','w')
for word in a:
if word[0] in vowels:
sfile = open('second.txt','a')
sfile.write(f'{word} ')
sfile = open('second.txt','r')
return sfile.read()
print(addwordswithvowelstart())
OUTPUT:
21
#15. Write a function in Python to count and display number of vowels in text file.
CODE:
file1 = open('testfile.txt','r')
vowels = ['a', 'e', 'i', 'o', 'u']
vc = 0
for line in file1:
for char in line:
if char.lower() in vowels:
vc += 1
print(f'The number of vowels is {vc}')
OUTPUT:
22
#16. A binary file “student.dat” has structure [rollno,name, marks].
i. Write a user defined function insertRec() to input data for a student and add to student.dat.
ii. Write a function searchRollNo( r ) in Python which accepts the student’s rollno as parameter
and searches the record in the file “student.dat” and shows the details of student i.e. rollno, name
and marks (if found) otherwise shows the message as ‘No record found’.
CODE:
import pickle
def insertRec():
rollno = int(input("What is the roll number: "))
name = input("What is the name: ")
marks = float(input("What are the marks: "))
s = [rollno,name,marks]
studentdata.append(s)
with open('student.dat', 'wb') as studentdatafile:
pickle.dump(studentdata, studentdatafile)
def searchRollNo(r):
for i in studentdata:
if i[0] == r:
return i
return 'No record found'
studentdata = []
while True:
print('1. Add student \n2. Search for student details \n3. Print all students \n4. Exit Program')
choice = int(input("What do you want to do: "))
if choice == 1:
insertRec()
elif choice == 2:
rno = int(input("What is the roll number you want to search: "))
with open('student.dat', 'rb') as studentdatafile:
studentdata = pickle.load(studentdatafile)
print(searchRollNo(rno))
elif choice == 3:
with open('student.dat', 'rb') as studentdatafile:
studentdata = pickle.load(studentdatafile)
print(studentdata)
else:
break
23
OUTPUT:
24
#17. A binary file “emp.dat” has structure [EID,Ename, designation, salary].
i. Write a user defined function CreateEmp() to input data for a record and create a file emp.dat.
ii. Write a function display() in Python to display the details of all employees whose salary is
more than 50000.
CODE:
import pickle
def CreateEmp():
EID = int(input("Enter the Employee ID: "))
Ename = input("Enter Employee Name: ")
designation = input("Enter the Designation: ")
salary = int(input("Enter the Salary: "))
e = [EID, Ename, designation, salary]
Edata.append(e)
with open('emp.dat', 'wb') as employeedatafile:
pickle.dump(Edata, employeedatafile)
def display():
with open('emp.dat', 'rb') as employeedatafile:
Edata = pickle.load(employeedatafile)
for i in Edata:
if i[3] > 50000:
print(i)
if all(i[3] <= 50000 for i in Edata):
print('No record found')
Edata = []
while True:
print('1. Add Employee \n2. Print all Employees with salary greater than 50000 \n3. Exit
Program')
choice = int(input("What do you want to do: "))
if choice == 1:
CreateEmp()
elif choice == 2:
display()
elif choice == 3:
break
25
OUTPUT:
26
#18. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and add to “Book.dat” .
ii. Write a function CountRec(Author) in Python which accepts the Author name as parameter
and count and return number of books by the given Author are stored in the binary file
“Book.dat”.
CODE:
import pickle
def CreateFile():
BookNo = int(input("Enter the Book Number: "))
Book_Name = input("Enter Book Name: ")
Author = input("Enter the Author: ")
Price = int(input("Enter the Price: "))
b = [BookNo, Book_Name, Author, Price]
Bdata.append(b)
with open('Book.dat', 'wb') as bookdatafile:
pickle.dump(Bdata, bookdatafile)
def CountRec(Author):
c=0
for i in Bdata:
if i[2] == Author:
c += 1
return c
Bdata = []
while True:
print('1. Add Book \n2. Count books by Author \n3. Exit Program')
choice = int(input("What do you want to do: "))
if choice == 1:
CreateFile()
elif choice == 2:
Author = input("Enter the Author name: ")
with open('Book.dat', 'rb') as bookdatafile:
Bdata = pickle.load(bookdatafile)
print(CountRec(Author))
else:
break
27
OUTPUT:
28
#19. A binary file “STUDENT.DAT” has structure (admission_number, Name, Percentage).
Write a function countrec() in Python that would read contents of the file “STUDENT.DAT” and
display the details of those students whose percentage is above 75. Also display number of
students scoring above 75%.
CODE:
import pickle
def insertRec():
admissionno = int(input("What is the admission number: "))
name = input("What is the name: ")
percentage = float(input("What are is the percentage: "))
s = [admissionno,name,percentage]
studentdata.append(s)
with open('STUDENT.DAT', 'wb') as studentdatafile:
pickle.dump(studentdata, studentdatafile)
c=0
def countrec():
global c
for i in studentdata:
if i[2] >= 75:
c += 1
print(i)
return f"The number of students with 75% above are {c}"
studentdata = []
while True:
print('1. Add student \n2. Search for student with 75 percentage and above \n3. Print all
students \n4. Exit Program')
choice = int(input("What do you want to do: "))
if choice == 1:
insertRec()
elif choice == 2:
with open('STUDENT.DAT', 'rb') as studentdatafile:
studentdata = pickle.load(studentdatafile)
print(countrec())
c=0
elif choice == 3:
29
with open('STUDENT.DAT', 'rb') as studentdatafile:
studentdata = pickle.load(studentdatafile)
print(studentdata)
else:
break
OUTPUT:
30
#20. A binary file named “EMP.dat” has some records of the structure [EmpNo, EName, Post,
Salary]
(a) Write a user-defined function named NewEmp() to input the details of a new employee from
the user and store it in EMP.dat.
(b) Write a user-defined function named SumSalary(Post) that will accept an argument the post
of employees & read the contents of EMP.dat and calculate the SUM of salary of all employees
of that Post.
CODE:
import pickle
def NewEmp():
EmpNo = int(input("What is the employee number: "))
Ename = input("What is employees name: ")
Post = input("What is their post: ")
Salary = int(input("What is the salary: "))
E = [EmpNo,Ename,Post,Salary]
Employeesdata.append(E)
with open('EMP.dat','wb') as EmployeeFile:
pickle.dump(Employeesdata,EmployeeFile)
s=0
def SumSalary(Post):
global s
for i in Employeesdata:
if i[2] == Post:
s += i[3]
return f"The sum of their salaries is {s}"
Employeesdata = []
while True:
print("1. Add employee \n2. Add salaries of employees with a specific post \n3. Print all
employees data \n4. Exit")
ch = int(input("What do you want to do: "))
if ch == 1:
NewEmp()
elif ch == 2:
POST = input("What post to sum for: ")
with open("EMP.dat",'rb') as EmployeeFile:
Employeesdata = pickle.load(EmployeeFile)
print(SumSalary(POST))
s= 0
31
elif ch == 3:
with open("EMP.dat",'rb') as EmployeeFile:
Employeesdata = pickle.load(EmployeeFile)
print(Employeesdata)
else:
break
OUTPUT:
32
#21. A binary file “Items.dat” has structure as [ Code,Description, Price ].
i. Write a user defined function MakeFile( ) to input multiple items from the user and add to
Items.dat
ii. Write a function SearchRec(Code) in Python which will accept the code as parameter and
search and display the details of the corresponding code on screen from Items.dat.
CODE:
import pickle
def MakeFile():
Code = int(input("What is Item Code: "))
Description = input("Enter a description for it: ")
Price = int(input("What is the item price: "))
Items.append([Code,Description,Price])
with open('Items.dat','wb') as Itemfile:
pickle.dump(Items,Itemfile)
def SearchRec(Code):
with open('Items.dat','rb') as Itemfile:
pickle.load(Itemfile)
for i in Items:
if i[0] == Code:
return i[1]
Items = []
while True:
print('1. Add items \n2. Search for item using code \n3. Print all Items \n4. Exit')
ch = int(input('What do you want to do: '))
if ch== 1:
MakeFile()
elif ch ==2:
Code = int(input("What item code to search for: "))
print(SearchRec(Code))
elif ch ==3:
with open("Items.dat",'rb') as File:
i = pickle.load(File)
print(i)
else:
break
33
OUTPUT:
34
#22 Write a user defined function in Python to read the content from a text fileMYbook.txt,
count and display the number of blank spaces present in it
def count_blank_spaces():
try:
with open('MYbook.txt', 'r') as file:
content = file.read()
blank_spaces = content.count(' ')
print(f"Number of blank spaces: {blank_spaces}")
except FileNotFoundError:
print("The file 'MYbook.txt' does not exist.")
count_blank_space()
35
#22Write a function in Python to count the number of alphabets present in atext file
“NOTES.TXT”
def count_alphabets(filename):
count = 0
if char.isalpha():
count += 1
return count
filename = 'NOTES.TXT'
alphabet_count = count_alphabets(filename)
print(f'The number of alphabets in {filename} is: {alphabet_count}')
36
#23Write a function in Python to count and display the number of words startingwith a vowel
present in a given text file “ABC.TXT”
def count_words_starting_with_vowel(filename):
vowels = 'aeiouAEIOU'
count = 0
filename = 'ABC.TXT'
count_words_starting_with_vowel(filename)
37
#24Write a function which reads an already existing file “text1.txt” and writedigits (0-9) in to a
new text file “DIGIT.TXT” and non digit files into NONDIG.TXT
38
#25Write a function in Python to count the number of lines present in a text file“STORY.TXT”
def count_lines(filename):
with open(filename, 'r') as file:
lines = file.readlines()
print(f'The number of lines in {filename} is: {len(lines)}')
count_lines('STORY.TXT')
39
#26 .Assuming that a text file named TEXT1.TXT already contains some textwritten into it.
Write a function named vowelwords(), that reads the file TEXT1.TXT and creates a new file
named TEXT2.TXT , which shall containonly those words from the file TEXT1.TXT which
don’t start with an uppercase vowel.
def vowelwords():
with open('TEXT1.TXT', 'r') as file:
words = file.read().split()
vowelwords()
40
#27 .Write a program that displays the size of a text file in bytes.
import os
def file_size(filename):
size = os.path.getsize(filename)
print(f'The size of {filename} is: {size} bytes')
file_size('example.txt')
41
#28Write a function in Python to print the count of the word is as an independent word in a text
file DIALOGUE.TXT.For example , if the content of the file is This is his book. Is this book
good
def count_is_word(filename):
with open(filename, 'r') as file:
words = file.read().split()
count = words.count('is')
print(f'The count of the word "is" is: {count}')
count_is_word('DIALOGUE.TXT')
42
#29
Write an interactive Python program to read a text file and display the following :
(i) Frequency table of all the alphabetic characters
(ii)Number of numeric characters present in the file
def analyze_file(filename):
from collections import Counter
freq_table = Counter(alphabetic_chars)
analyze_file('example.txt')
43
#30 A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price]. i. Write a user
defined function createFile() to input data for a record and add to Book.dat. ii. Write a function
countRec(Author) in Python which accepts the Author name as parameter and count and return
number of books by the given Author are stored in the binary file "Book.dat"
import pickle
def createFile():
with open('Book.dat', 'ab') as file:
book_no = input('Enter Book Number: ')
book_name = input('Enter Book Name: ')
author = input('Enter Author: ')
price = float(input('Enter Price: '))
createFile()
import pickle
def countRec(author):
count = 0
with open('Book.dat', 'rb') as file:
while True:
try:
record = pickle.load(file)
if record[2] == author:
count += 1
except EOFError:
break
print(f'Number of books by {author}: {count}')
countRec('Author Name')
44
#31 A binary file "STUDENT.DAT" has structure (admission_number, Name, Percentage).
Write a function count_rec() in Python that would read contents of the file "STUDENT.DAT"
and display the details of those students whose percentage is above 75. Also display number of
students scoring above 75%
import pickle
def count_rec():
with open('STUDENT.DAT', 'rb') as file:
while True:
try:
record = pickle.load(file)
if record[2] > 75:
print(f'Admission Number: {record[0]}, Name: {record[1]}, Percentage:
{record[2]}')
except EOFError:
break
count_rec()
45
#32 Given a binary file employee.dat, created using dictionary object having keys: (empcode,
name, and salary)
Write a python function that add one more record at the end of file. Write a python function that
display all employee records whose salary is more that 30000
import pickle
def add_record():
with open('employee.dat', 'ab') as file:
empcode = input('Enter Employee Code: ')
name = input('Enter Name: ')
salary = float(input('Enter Salary: '))
import pickle
def display_high_salary():
with open('employee.dat', 'rb') as file:
while True:
try:
record = pickle.load(file)
if record['salary'] > 30000:
print(record)
except EOFError:
break
display_high_salary()
46
#33
Write a function to search and display details of student whose rollno is '1005' from the binary
file student.dat having structure [rollno, name, class and fees].
import pickle
def search_student(rollno):
with open('student.dat', 'rb') as file:
while True:
try:
record = pickle.load(file)
if record[0] == rollno:
print(f'Roll No: {record[0]}, Name: {record[1]}, Class: {record[2]}, Fees:
{record[3]}')
return
except EOFError:
break
print('No record found')
# Example usage
search_student('1005')
47
#34
A binary file school.dat has structure(rollno, name, class, fees)
Write a definition for function total_fees( ) that reads each object of file and calculate the total
fees of students and display the same.
import pickle
def total_fees():
total = 0
with open('school.dat', 'rb') as file:
while True:
try:
record = pickle.load(file)
total += record[3]
except EOFError:
break
print(f'Total fees: {total}')
# Example usage
total_fees()
48
#35
A binary file players.dat, containing records of following list format: [code, name, country and
total runs]
Write a python function that display all records where player name starts from 'A
import pickle
def display_players_starting_with_A():
with open('players.dat', 'rb') as file:
while True:
try:
record = pickle.load(file)
if record[1].startswith('A'):
print(record)
except EOFError:
break
display_players_starting_with_A()
Write a python function that accepts a country as an argument and count and display the number
of players of that country.
import pickle
def count_players_by_country(country):
count = 0
with open('players.dat', 'rb') as file:
while True:
try:
record = pickle.load(file)
if record[2] == country:
count += 1
except EOFError:
break
49
print(f'Number of players from {country}: {count}')
count_players_by_country('USA')
Write a python function that adds one record at the end of file
import pickle
def add_player_record():
with open('players.dat', 'ab') as file:
code = input('Enter Player Code: ')
name = input('Enter Player Name: ')
country = input('Enter Country: ')
total_runs = int(input('Enter Total Runs: '))
add_player_record()
50
#39
Given a binary file game.dat, containing records of following list format: [game_name,
participants]
import pickle
51
#40
Write a function in Python that would read contents from the file game.dat and creates a file
named basket.dat copying only those records from game.dat where the game name is "Basket
Ball"
import pickle
def display_basketball_games():
with open('game.dat', 'rb') as infile:
while True:
try:
record = pickle.load(infile)
if record[0] == 'Basket Ball':
print(record)
except EOFError:
break
display_basketball_games()
52
#41
Write a python program to create a csv file dvd.csv and write 10 records in it Dvd
id,dvd name,qty,price. Display those dvd details whose dvd price is more than 25.
import csv
def create_and_write_dvd_csv():
with open('dvd.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['id', 'dvd name', 'qty', 'price'])
records = [
[1, 'Movie A', 10, 30],
[2, 'Movie B', 15, 20],
[3, 'Movie C', 5, 50],
[4, 'Movie D', 7, 15],
[5, 'Movie E', 12, 40],
[6, 'Movie F', 9, 22],
[7, 'Movie G', 8, 35],
[8, 'Movie H', 11, 18],
[9, 'Movie I', 6, 60],
[10, 'Movie J', 13, 25]
]
writer.writerows(records)
create_and_write_dvd_csv()
53
54
#42
Write a program to search the record from "data.csv" according to the admission number input
from the user. Structure of record saved in "data.csv" is [Admno, Name,Class, Section,Marks].
import csv
def search_record(admno):
with open('data.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader) # Skip header
for row in reader:
if row[0] == admno:
print('Record found:', row)
return
print('No record found.')
search_record('12345')
55
#43
Write a program to insert the record in the file "data.csv". The record structure is:
{FurnitureCode, FurnitureName, Price}
import csv
def insert_record():
with open('data.csv', 'a', newline='') as file:
writer = csv.writer(file)
code = input('Enter FurnitureCode: ')
name = input('Enter FurnitureName: ')
price = input('Enter Price: ')
writer.writerow([code, name, price])
insert_record()
56
#44
Write a program to display the recors from "Prodcut.csv" file where the price is more than 300.
The structure save dint he file is [Productid, Productname, Price]
import csv
def display_expensive_products():
with open('Product.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader) # Skip header
print('Products with price greater than 300:')
for row in reader:
if float(row[2]) > 300:
print(row)
display_expensive_products()
57
#45
Write a program to count the number of records present in "data.csv".
import csv
def count_records():
with open('data.csv', 'r') as file:
reader = csv.reader(file)
header = next(reader) # Skip header
count = sum(1 for row in reader)
print(f'Number of records: {count}')
count_records()
58
#46
write a program to modify the record present in "data.csv". The structure of the record is
[RollNum, Name, Marks]
import csv
# Example usage
modify_record('101', 'Jane Doe', '90')
The record with RollNum 101 is updated to ['101', 'Jane Doe', '90'] in data.csv.
59