shuvhamkar
1. Read a text file line by line and display each word separated
by a #.
Source Code: -
with open('Shuvhamkar.txt', 'r') as file:
for line in file:
words = line.split()
if len(words) > 0:
print(words[0], end="")
for word in words[1:]:
print("#" + word, end="")
print()
Output: -
Hello#python#I’m#Shuvhamkar#and#I’m#an#CS#student
5321
shuvhamkar
2. Read a text file and display the number of vowels/
consonants/ uppercase/lowercase character in the file.
Source Code: -
with open('Shuvhamkar.txt', 'r') as file:
vowels = consonants = uppercase = lowercase = 0
vowel_set = "AEIOUaeiou"
for line in file:
for char in line:
if char.isalpha():
if char in vowel_set:
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
if char.islower():
lowercase += 1
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Uppercase characters: {uppercase}")
print(f"Lowercase characters: {lowercase}")
5321
shuvhamkar
Output:-
Vowels: 11
Consonants: 23
Uppercase Characters: 3
Lowercase Characters: 31
5321
shuvhamkar
3. Remove all the lines that contain the character ‘a’ in a file
and write it to another file.
Source Code: -
with open('Shuvhamkar.txt', 'r') as infile:
with open('test.txt', 'w') as outfile:
for line in infile:
if 'a' not in line.lower():
outfile.write(line)
print("data has been written successfully")
Output: -
data has been written successfully
5321
shuvhamkar
4. Create a Binary file with name and roll number Search for a
given roll number and display the name, if not found display
appropriate message.
Source Code: -
import pickle
with open('students.bin', 'wb') as file:
students = [
('Shuvhamkar', 28),
('Sparsh', 29),
('Suhani', 30),
('Shreya', 27)
]
pickle.dump(students, file)
print("Binary file created successfully.")
search_roll = int(input("Enter the roll number to search: "))
with open('students.bin', 'rb') as file:
students = pickle.load(file)
for student in students:
name, roll_number = student
if roll_number == search_roll:
print(f"Roll number {roll_number} found. Name:
{name}")
break
5321
shuvhamkar
else:
print(f"Roll number {search_roll} not found.")
Output:-
Binary file created successfully.
Enter the roll number to search: 28
Roll number 28 found. Name: Shuvhamkar
5321
shuvhamkar
5. Create aa binary file with roll number, name, marks. Input a
roll number and update the marks.
Source Code: -
import pickle
with open('students.bin', 'wb') as file:
students = [
(28, 'Shuvhamkar', 89),
(29, 'Abhishek', 90),
(30, 'Shourya', 93),
(27, 'Shreya', 92)
]
pickle.dump(students, file)
print("Binary file created successfully.")
try:
search_roll = int(input("Enter the roll number to update
marks: "))
new_marks = int(input("Enter the new marks: "))
except ValueError:
print("Please enter valid integer values for roll number
and marks.")
exit()
try:
with open('students.bin', 'rb') as file:
students = pickle.load(file)
5321
shuvhamkar
except (FileNotFoundError, EOFError) as e:
print("Error reading the binary file:", e)
exit()
updated_students = []
updated = False
for roll_number, name, marks in students:
if roll_number == search_roll:
updated_students.append((roll_number, name,
new_marks))
print(f"Marks updated for {name}. New marks:
{new_marks}")
updated = True
else:
updated_students.append((roll_number, name, marks))
if not updated:
print(f"Roll number {search_roll} not found.")
with open('students.bin', 'wb') as file:
pickle.dump(updated_students, file)
print("Binary file updated successfully.")
Output: -
Binary file created successfully.
Enter the roll number to update marks: 28
Enter the new marks: 90
Marks updated for Shuvhamkar. New marks: 90
5321
shuvhamkar
Binary file updated successfully.
6. Write a random number generator that generates numbers
between 1 and 6 (Simulates a dice).
Source Code: -
import random
while True:
input("Press Enter to roll the dice...")
dice_roll = random.randint(1, 6)
print(f"You rolled a {dice_roll}!")
again = input("Do you want to roll again? (y/n): ")
if again.lower() != 'y':
break
Output: -
Press Enter to roll the dice...
You rolled a 2!
Do you want to roll again? (y/n): y
Press Enter to roll the dice...
You rolled a 1!
Do you want to roll again? (y/n): n
5321
shuvhamkar
7. Write a python program to implement a stack using list.
Source Code:-
stack = []
stack.append(10)
print(f"Pushed 10 onto the stack.")
stack.append(20)
print(f"Pushed 20 onto the stack.")
stack.append(30)
print(f"Pushed 30 onto the stack.")
print("Current stack:", stack)
if stack:
top_element = stack[-1]
print("Top element:", top_element)
else:
print("Stack is empty! No top element.")
if stack:
popped_element = stack.pop()
print(f"Popped element: {popped_element}")
else:
print("Stack is empty! Cannot pop.")
if stack:
popped_element = stack.pop()
print(f"Popped element: {popped_element}")
5321
shuvhamkar
print("Stack is empty! Cannot pop.")
print("Current stack after popping:", stack)
print("Current stack size:", len(stack))
if stack:
popped_element = stack.pop()
print(f"Popped element: {popped_element}")
else:
print("Stack is empty! Cannot pop.")
if stack:
popped_element = stack.pop()
print(f"Popped element: {popped_element}")
else:
print("Stack is empty! Cannot pop.")
Output:-
Pushed 10 onto the stack.
Pushed 20 onto the stack.
Pushed 30 onto the stack.
Current stack: [10, 20, 30]
Top element: 30
Popped element: 30
Popped element: 20
Current stack after popping: [10]
Current stack size: 1
Popped element: 10
5321
shuvhamkar
Stack is empty! Cannot pop.
5321
shuvhamkar
8. Create a CSV file by entering user-id and password, read and
search the password for given user-id.
Source Code: -
import csv
filename = 'user_data.csv'
while True:
user_id = input("Enter user ID (or type 'exit' to finish): ")
if user_id.lower() == 'exit':
break
password = input("Enter password: ")
with open(filename, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow([user_id, password])
print(f"User ID and password saved to {filename}.")
search_id = input("Enter user ID to search for password: ")
found = False
with open(filename, mode='r') as file:
reader = csv.reader(file)
for row in reader:
if row[0] == search_id:
print(f"Password for user ID '{search_id}': {row[1]}")
found = True
break
5321
shuvhamkar
if not found:
print(f"No password found for user ID '{search_id}'.")
Output: -
Enter user ID (or type 'exit' to finish): 1
Enter password: 12345
Enter user ID (or type 'exit' to finish): 2
Enter password: 2345
Enter user ID (or type 'exit' to finish): 3
Enter password: 12345
Enter user ID (or type 'exit' to finish): exit
User ID and password saved to user_data.csv.
Enter user ID to search for password: 2
Password for user ID '2': 2345
5321
shuvhamkar
9. Write a program to read a list in binary file.
Source Code:-
Import pickle
with open(‘list_data.bin’,’rb’) as file:
my_list = pickle.load(file)
print(my_list)
Output: -
[10,20,30,40,50]
5321
shuvhamkar
10. How would you write a python function to create a binary file.
Source code: -
def create_binary_file(filename):
with open(filename,’wb’) as file:
print(“Binary file ‘{filename}’ created successfully.”)
create_binary_file(“student.bin”)
Output: -
Binary file ‘student.bin’ created successfully.
5321
shuvhamkar
11. Create a Class table and insert data using SQL
command.
Source Code:-
5321
shuvhamkar
12. ALTER the above table to add new attributes / modify
data type /drop attribute.
Source Code:-
5321
shuvhamkar
13. UPDATE the above table to modify data.
Source Code:-
5321
shuvhamkar
14. OREDER BY to display data of above table in ascending/
descending order.
Source Code: -
5321
shuvhamkar
15. DELETE to remove tuple(s) from above table.
Source Code:-
5321
shuvhamkar
16. To count the frequency of words in a file
Python Code:
from collections import Counter
def word_count(fname):
with open(fname) as f:
return Counter(f.read().split())
print("Number of words in the
file :",word_count("test.txt"))
5321
shuvhamkar
17. Write a Python program to count the number of lines
in a text file
Python Code:
def file_lengthy(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
print("Number of lines in the file:
",file_lengthy("test.txt"))
OUTPUT:
Number of lines in the file: 6
5321
shuvhamkar
18. Write a Python program to extract characters from various text
files and puts them into a list.
Python Code:
import glob
char_list = []
files_list = glob.glob("*.txt")
for file_elem in files_list:
with open(file_elem, "r") as f:
char_list.append(f.read())
print(char_list)
5321
shuvhamkar
19. Write a Python program to remove newline characters from a file.
Python Code:
def remove_newlines(fname):
flist = open(fname).readlines()
return [s.rstrip('\n') for s in flist]
print(remove_newlines("test.txt"))
5321
shuvhamkar
20. Write a Python program to create a file where all letters of English
alphabet are listed by specified number of letters on each line.
Python Code:
import string
def letters_file_line(n):
with open("words1.txt", "w") as f:
alphabet = string.ascii_uppercase
letters = [alphabet[i:i + n] + "\n" for i in
range(0, len(alphabet), n)]
f.writelines(letters)
letters_file_line(3)
Output:
words1.txt
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
5321
shuvhamkar
21. Write a function push(student) and pop(student) to add a new
student name and remove a student name from a list student,
considering them to act as PUSH and POP operations of stack
Data Structure in Python.
SOURCE CODE:
st=[]
def push(st):
sn=input("Enter name of student")
st.append(sn)
def pop(st):
if(st== []):
print("Stack is empty")
else:
print("Deleted student name:",st.pop())
5321
shuvhamkar
22. Write a function push(number) and pop(number) to add a
number (Accepted from the user) and remove a number from a
list of numbers, considering them act as PUSH and POP operations
of Data Structure in Python.
SOURCE CODE:
st=[]
def push(st):
sn=input("Enter any Number")
st.append(sn)
def pop(st):
if(st= = []):
print("Stack is empty")
else:
print("Deleted Number is:",st.pop())
5321
shuvhamkar
23. Write a menu based program to add, delete and display the
record of hostel using list as stack data structure in python.
Record of hostel contains the fields: Hostel number, Total
Students and Total Rooms
SOURCE CODE:
hostel_records = []
def add_record():
hostel_number = input("Enter the hostel number: ")
total_students = int(input("Enter the total number of students: "))
total_rooms = int(input("Enter the total number of rooms: "))
hostel_records.append([hostel_number, total_students, total_rooms])
print("Record added successfully.")
def delete_record():
hostel_number = input("Enter the hostel number to delete the record:
")
for record in hostel_records:
if record[0] == hostel_number:
hostel_records.remove(record)
print("Record deleted successfully.")
return
print("Record not found.")
def display_records():
if not hostel_records:
print("No records to display.")
5321
shuvhamkar
return
print("Hostel Number\tTotal Students\tTotal Rooms")
for record in hostel_records:
print(record[0], "\t\t", record[1], "\t\t", record[2])
while True:
print("1. Add Record")
print("2. Delete Record")
print("3. Display Records")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
add_record()
elif choice == 2:
delete_record()
elif choice == 3:
display_records()
elif choice == 4:
break
else:
print("Invalid choice. Try again.")
OUTPUT:
5321
shuvhamkar
24. Write a program to show the detail of the student who scored
the highest marks. Data stored in "Data.csv" is given below:
Rollno,Name,Marks
1,Shreya,35
2,Shuvhamkar,36
3,Sparsh,32
4,Suhani,35
SOURCE CODE:
import csv f=open("data.csv","r")
d=csv.reader(f)
next(f)
max=0
for i in d:
if int(i[2])>max:
max=int([2])
f.close() f=open("data.csv","r") d=csv.reader(f)
next(f)
5321
shuvhamkar
for i in d:
if int(i[2])==max
print(i)
f.close()
OUTPUT:
['2', 'Shuvhamkar', '37']
5321
shuvhamkar
25. Write a program to display all the records from
product.csv whose price is more than 300. Format of
record stored in product.csv is product id, product name,
price,.
SOURCE CODE:
import csv f=open("product.csv", "r")
d=csv.reader(f)
next(f)
print("product whose price more than 300")
print()
for i in d:
if int(i[2])>300:
print("Product id =", i[0])
print("Product Name", i[1])
print("Product Price =", i[2])
print(" -------------------------")
5321
shuvhamkar
f.close()
OUTPUT:
5321
shuvhamkar
26. To create a table garment by user’s data and inserting
rows into garment table
5321
shuvhamkar
27. To display contents of garment table
5321
shuvhamkar
5321
shuvhamkar
28.To display codes and names of those garments that
have their name starting with “ladies”
5321
shuvhamkar
29.To display names,codes and prices of those garments
that have price in range 1000.00 to 1500.00(both 1000.00
and 1500.00 included)
5321
shuvhamkar
30.Increase the price of all garments in the table by 15%.
5321