9.
Menu-driven program to create user defined functions to perform the following Text file
(Story.txt) operations: a) To write data to a text file (Any Sample text data) b) To read the entire
contents of the file and display it c) To print the statistics of the file. Read the text file and display the
total no. of characters, Total no of words and total no of digits.
def write_to_file():
file = open("Story.txt", "w")
data = input("Enter text to write to the file:\n")
file.write(data)
file.close()
print("Data written to Story.txt")
def read_file():
try:
file = open("Story.txt", "r")
content = file.read()
print("\nContents of Story.txt:\n", content)
file.close()
except FileNotFoundError:
print("Story.txt not found.")
def file_statistics():
try:
file = open("Story.txt", "r")
content = file.read()
chars = len(content)
words = len(content.split())
digits = sum(c.isdigit() for c in content)
print("\nStatistics of Story.txt:")
print("Total characters:", chars)
print("Total words:", words)
print("Total digits:", digits)
file.close()
except FileNotFoundError:
print("Story.txt not found.")
def main():
while True:
print("\n1. Write to file")
print("2. Read file")
print("3. Show file statistics")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
write_to_file()
elif choice == '2':
read_file()
elif choice == '3':
file_statistics()
elif choice == '4':
break
else:
print("Invalid choice.")
main()
10) Menu-driven program to create user defined functions to perform the following Text file
(Story.txt) operations: a) Read the contents of the text file line by line and display it.(File should be
created before) b) Display all the lines starting with a letter‘s’. c) Display each word separated by a #
symbol.
def read_lines():
try:
file = open("Story.txt", "r")
print("\nReading file line by line:")
for line in file:
print(line.strip())
file.close()
except FileNotFoundError:
print("Story.txt not found.")
def lines_starting_with_s():
try:
file = open("Story.txt", "r")
print("\nLines starting with 's':")
for line in file:
if line.startswith('s') or line.startswith('S'):
print(line.strip())
file.close()
except FileNotFoundError:
print("Story.txt not found.")
def words_separated_by_hash():
try:
file = open("Story.txt", "r")
print("\nWords separated by #:")
for line in file:
words = line.split()
print("#".join(words))
file.close()
except FileNotFoundError:
print("Story.txt not found.")
def main():
while True:
print("\n1. Read file line by line")
print("2. Show lines starting with 's'")
print("3. Show words separated by #")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
read_lines()
elif choice == '2':
lines_starting_with_s()
elif choice == '3':
words_separated_by_hash()
elif choice == '4':
break
else:
print("Invalid choice.")
main()
11) Menu-driven program to perform the following operations on a binary file ‘Player.dat’, which has
the following structure: Player_id, Player_name, Player_game]. a) Create a function File_Create () to
add records into the file. b) Create a function File_Read () to read the records c) Create a function
Search_Data () to search for a particular Player using his Player_id. If found, print the Player details.
Otherwise print appropriate message.
import pickle
# Function to create and add records to the binary file
def File_Create():
with open("Player.dat", "ab") as file: # Append mode for binary files
Player_id = input("Enter Player ID: ")
Player_name = input("Enter Player Name: ")
Player_game = input("Enter Player Game: ")
player = [Player_id, Player_name, Player_game]
pickle.dump(player, file) # Write record to binary file
print("Player record added successfully.")
# Function to read and display all records from the binary file
def File_Read():
try:
with open("Player.dat", "rb") as file:
print("\nPlayer records:")
while True:
try:
player = pickle.load(file) # Read each record
print(player)
except EOFError: # End of file reached
break
except FileNotFoundError:
print("Player.dat not found.")
# Function to search for a player by Player_id
def Search_Data():
found = False
try:
with open("Player.dat", "rb") as file:
search_id = input("Enter Player ID to search: ")
while True:
try:
player = pickle.load(file)
if player[0] == search_id:
print("\nPlayer found:", player)
found = True
break
except EOFError:
break
if not found:
print("Player ID not found.")
except FileNotFoundError:
print("Player.dat not found.")
# Menu-driven program
def main():
while True:
print("\n1. Add Player Record")
print("2. Read All Player Records")
print("3. Search for Player by ID")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
File_Create()
elif choice == '2':
File_Read()
elif choice == '3':
Search_Data()
elif choice == '4':
break
else:
print("Invalid choice.")
main()
12) Menu-driven program to perform the following operations on a binary file ‘Employee.dat’, which
has the structure as [empid, empname, salary, design]. a) Create a function File_Create () to add
records into the file. b) Create a function File_Read () to read the records (employee data) from file.
c) Create a function Update_Data () to update the salary of employees whose designation is
‘Manager’ by Rs.5000/- and display the updated data
import pickle
# Function to create and add records to the binary file
def File_Create():
with open("Employee.dat", "ab") as file: # Append mode for binary files
empid = input("Enter Employee ID: ")
empname = input("Enter Employee Name: ")
salary = float(input("Enter Salary: "))
design = input("Enter Designation: ")
employee = [empid, empname, salary, design]
pickle.dump(employee, file) # Write record to binary file
print("Employee record added successfully.")
# Function to read and display all employee records from the binary file
def File_Read():
try:
with open("Employee.dat", "rb") as file:
print("\nEmployee records:")
while True:
try:
employee = pickle.load(file) # Read each record
print(employee)
except EOFError: # End of file reached
break
except FileNotFoundError:
print("Employee.dat not found.")
# Function to update salary of employees with designation 'Manager'
def Update_Data():
try:
updated_employees = []
found = False
with open("Employee.dat", "rb") as file:
while True:
try:
employee = pickle.load(file)
if employee[3] == 'Manager': # Check if designation is 'Manager'
employee[2] += 5000 # Increase salary by Rs. 5000
found = True
updated_employees.append(employee)
except EOFError:
break
if found:
with open("Employee.dat", "wb") as file:
for employee in updated_employees:
pickle.dump(employee, file) # Write updated records back to the file
print("Salaries updated for 'Manager' employees.")
File_Read() # Display updated records
else:
print("No employees with the designation 'Manager' found.")
except FileNotFoundError:
print("Employee.dat not found.")
# Menu-driven program
def main():
while True:
print("\n1. Add Employee Record")
print("2. Read All Employee Records")
print("3. Update Salary of Managers")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
File_Create()
elif choice == '2':
File_Read()
elif choice == '3':
Update_Data()
elif choice == '4':
break
else:
print("Invalid choice.")
main()
13) Menu-driven program to perform the following operations on a CSV file ‘Login.csv’, which has
the structure as [uid, passwd]: a) Create a function Create_csv () to add records to the file. b) Create
a function Read_csv() to read and display all the records from the file. c) Create a function
Search_csv() to search whether a user exists or not with the uid which is passed as an argument.
import csv
# Function to create and add records to the CSV file
def Create_csv():
with open("Login.csv", "a", newline='') as file: # Append mode for CSV
writer = csv.writer(file)
uid = input("Enter User ID: ")
passwd = input("Enter Password: ")
writer.writerow([uid, passwd])
print("Record added successfully.")
# Function to read and display all records from the CSV file
def Read_csv():
try:
with open("Login.csv", "r") as file:
reader = csv.reader(file)
print("\nLogin records:")
for row in reader:
print(row)
except FileNotFoundError:
print("Login.csv not found.")
# Function to search whether a user exists with the given uid
def Search_csv(uid):
found = False
try:
with open("Login.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == uid: # Check if uid matches
print("\nUser found:", row)
found = True
break
if not found:
print("User ID not found.")
except FileNotFoundError:
print("Login.csv not found.")
# Menu-driven program
def main():
while True:
print("\n1. Add Login Record")
print("2. Read All Login Records")
print("3. Search for User by ID")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
Create_csv()
elif choice == '2':
Read_csv()
elif choice == '3':
uid = input("Enter User ID to search: ")
Search_csv(uid)
elif choice == '4':
break
else:
print("Invalid choice.")
main()
14) Menu-driven program to perform the following operations on a CSV file ‘Address.csv’, which has
the structure [Name, Mob_no, email] a) Create a function Create_csv () to add records to the file. b)
Create a function Read_csv() to read and display all the records from the file. c) Create a function
Search_csv() to search for a mobile number, if found then write only those records to a new csv file
‘NewAddress.csv’. If not found, print appropriate message.
import csv
# Function to create and add records to the CSV file
def Create_csv():
with open("Address.csv", "a", newline='') as file: # Append mode for CSV
writer = csv.writer(file)
name = input("Enter Name: ")
mob_no = input("Enter Mobile Number: ")
email = input("Enter Email: ")
writer.writerow([name, mob_no, email])
print("Record added successfully.")
# Function to read and display all records from the CSV file
def Read_csv():
try:
with open("Address.csv", "r") as file:
reader = csv.reader(file)
print("\nAddress records:")
for row in reader:
print(row)
except FileNotFoundError:
print("Address.csv not found.")
# Function to search for a mobile number and write found records to 'NewAddress.csv'
def Search_csv(mob_no):
found = False
try:
with open("Address.csv", "r") as file:
reader = csv.reader(file)
with open("NewAddress.csv", "w", newline='') as new_file: # Create new CSV for found
records
writer = csv.writer(new_file)
for row in reader:
if row[1] == mob_no: # Check if mobile number matches
writer.writerow(row) # Write matched record to new file
found = True
if found:
print(f"Records with Mobile Number {mob_no} written to 'NewAddress.csv'.")
else:
print("Mobile Number not found.")
except FileNotFoundError:
print("Address.csv not found.")
# Menu-driven program
def main():
while True:
print("\n1. Add Address Record")
print("2. Read All Address Records")
print("3. Search for Mobile Number and Write to New File")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
Create_csv()
elif choice == '2':
Read_csv()
elif choice == '3':
mob_no = input("Enter Mobile Number to search: ")
Search_csv(mob_no)
elif choice == '4':
break
else:
print("Invalid choice.")
main()
15) Menu-driven program to implement Stack using a list data-structure, to perform the following
operations: a) To Push an object containing Doc_ID and Doc_name of doctors who specialize in
"ENT" to the stack. b) To Pop the objects from the stack and display them. c) To display the elements
of the stack (after performing PUSH or POP)
# Stack implementation using a list
stack = []
# Function to push an object to the stack
def push():
Doc_ID = input("Enter Doctor ID: ")
Doc_name = input("Enter Doctor Name: ")
doctor = {"Doc_ID": Doc_ID, "Doc_name": Doc_name}
stack.append(doctor) # Push doctor object to the stack
print(f"Doctor {Doc_name} added to the stack.")
# Function to pop an object from the stack
def pop():
if len(stack) == 0:
print("Stack is empty. No doctor to pop.")
else:
doctor = stack.pop() # Pop the top doctor from the stack
print(f"Popped Doctor: {doctor}")
# Function to display the stack
def display_stack():
if len(stack) == 0:
print("Stack is empty.")
else:
print("\nDoctors in the stack:")
for doctor in stack:
print(doctor)
# Menu-driven program
def main():
while True:
print("\n1. Push Doctor to Stack")
print("2. Pop Doctor from Stack")
print("3. Display Stack")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
push()
elif choice == '2':
pop()
elif choice == '3':
display_stack()
elif choice == '4':
break
else:
print("Invalid choice.")
main()
16) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database school, create a table student with fields as Rollno, Stu_Name, Stream and
Percentage. Then insert 5 records into it. b) Display all the records from the table
import mysql.connector
# Connect to MySQL
def connect_to_mysql():
return mysql.connector.connect(
host="localhost", # Change this to your MySQL host if necessary
user="root", # Replace with your MySQL username
password="your_password" # Replace with your MySQL password
# Create a database, table and insert 5 records
def create_database_and_insert():
conn = connect_to_mysql()
cursor = conn.cursor()
# Create database and table
cursor.execute("CREATE DATABASE IF NOT EXISTS school")
cursor.execute("USE school")
cursor.execute("CREATE TABLE IF NOT EXISTS student (Rollno INT, Stu_Name VARCHAR(100),
Stream VARCHAR(50), Percentage FLOAT)")
# Insert 5 records
cursor.execute("INSERT INTO student VALUES (1, 'John Doe', 'Science', 88.5)")
cursor.execute("INSERT INTO student VALUES (2, 'Jane Smith', 'Commerce', 92.0)")
cursor.execute("INSERT INTO student VALUES (3, 'Emily Davis', 'Arts', 79.5)")
cursor.execute("INSERT INTO student VALUES (4, 'Michael Brown', 'Science', 85.0)")
cursor.execute("INSERT INTO student VALUES (5, 'Sarah Johnson', 'Commerce', 89.3)")
conn.commit() # Save changes
print("Database, table, and 5 records created.")
conn.close() # Close connection
# Display all records from the student table
def display_records():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE school")
cursor.execute("SELECT * FROM student")
# Print records
for row in cursor.fetchall():
print(row)
conn.close() # Close connection
# Menu-driven program
def main():
while True:
print("\n1. Create Database and Insert Records")
print("2. Display All Records")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_database_and_insert()
elif choice == '2':
display_records()
elif choice == '3':
break
else:
print("Invalid choice, try again.")
main()
17) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database Company, create a table Product with fields as Pid, Pname, Qty and Price. Then
insert 5 records into it. b) Display all the records from the table c) Read records from student table
and search for a particular student based on the Pid
import mysql.connector
# Function to connect to MySQL
def connect_to_mysql():
return mysql.connector.connect(
host="localhost", # Change if necessary
user="root", # Replace with your MySQL username
password="your_password" # Replace with your MySQL password
# Create database, table and insert records
def create_database_and_insert():
conn = connect_to_mysql()
cursor = conn.cursor()
# Create database and table
cursor.execute("CREATE DATABASE IF NOT EXISTS Company")
cursor.execute("USE Company")
cursor.execute("""
CREATE TABLE IF NOT EXISTS Product (
Pid INT PRIMARY KEY,
Pname VARCHAR(100),
Qty INT,
Price FLOAT
""")
# Insert 5 records
products = [
(1, 'Product1', 10, 100.50),
(2, 'Product2', 20, 150.75),
(3, 'Product3', 15, 200.00),
(4, 'Product4', 25, 120.40),
(5, 'Product5', 30, 250.99)
cursor.executemany("INSERT INTO Product VALUES (%s, %s, %s, %s)", products)
conn.commit() # Save changes
print("Database, table, and records created.")
conn.close() # Close connection
# Display all records from the Product table
def display_records():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("SELECT * FROM Product")
# Print records
for row in cursor.fetchall():
print(row)
conn.close() # Close connection
# Search for a product based on Pid
def search_product(pid):
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("SELECT * FROM Product WHERE Pid = %s", (pid,))
# Fetch and print the product details
product = cursor.fetchone()
if product:
print("Product found:", product)
else:
print("Product not found.")
conn.close() # Close connection
# Menu-driven program
def main():
while True:
print("\n1. Create Database and Insert Records")
print("2. Display All Records")
print("3. Search Product by Pid")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_database_and_insert()
elif choice == '2':
display_records()
elif choice == '3':
pid = int(input("Enter Product ID to search: "))
search_product(pid)
elif choice == '4':
break
else:
print("Invalid choice, try again.")
main()
18) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database Company, create a table Employee with fields as Empid, Empname, designation
and Salary. Then insert 5 records into it. b) Update the salary of an employee by 5000 whose
designation as ‘Manager’ c) Display all the records from the table. d) Delete the records from
employee based on their empid.
import mysql.connector
# Function to connect to MySQL
def connect_to_mysql():
return mysql.connector.connect(
host="localhost", # Change if necessary
user="root", # Replace with your MySQL username
password="your_password" # Replace with your MySQL password
# Create database, table and insert records
def create_database_and_insert():
conn = connect_to_mysql()
cursor = conn.cursor()
# Create database and table
cursor.execute("CREATE DATABASE IF NOT EXISTS Company")
cursor.execute("USE Company")
cursor.execute("""
CREATE TABLE IF NOT EXISTS Employee (
Empid INT PRIMARY KEY,
Empname VARCHAR(100),
designation VARCHAR(50),
Salary FLOAT
""")
# Insert 5 records
employees = [
(1, 'Alice', 'Manager', 60000),
(2, 'Bob', 'Developer', 50000),
(3, 'Charlie', 'Manager', 70000),
(4, 'David', 'Analyst', 40000),
(5, 'Eva', 'Designer', 45000)
cursor.executemany("INSERT INTO Employee VALUES (%s, %s, %s, %s)", employees)
conn.commit() # Save changes
print("Database, table, and records created.")
conn.close() # Close connection
# Update salary of employees with designation 'Manager'
def update_salary():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("UPDATE Employee SET Salary = Salary + 5000 WHERE designation = 'Manager'")
conn.commit() # Save changes
print("Salaries updated for Managers.")
conn.close() # Close connection
# Display all records from the Employee table
def display_records():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("SELECT * FROM Employee")
# Print records
for row in cursor.fetchall():
print(row)
conn.close() # Close connection
# Delete employee record based on Empid
def delete_employee(empid):
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("DELETE FROM Employee WHERE Empid = %s", (empid,))
conn.commit() # Save changes
print("Employee record deleted.")
conn.close() # Close connection
# Menu-driven program
def main():
while True:
print("\n1. Create Database and Insert Records")
print("2. Update Salary for Managers")
print("3. Display All Records")
print("4. Delete Employee by Empid")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_database_and_insert()
elif choice == '2':
update_salary()
elif choice == '3':
display_records()
elif choice == '4':
empid = int(input("Enter Employee ID to delete: "))
delete_employee(empid)
elif choice == '5':
break
else:
print("Invalid choice, try again.")
main()
19) Menu driven program to integrate MySQL with Python and perform the following operations: a)
Create a database Company, create a table create a table Client with fields as C_ID, ClientName, City.
b) Read records from the table and display those records whose city is ‘Delhi’. c) Delete the records
from table based on their client id d) Display all the records.
import mysql.connector
# Function to connect to MySQL
def connect_to_mysql():
return mysql.connector.connect(
host="localhost", # Change if necessary
user="root", # Replace with your MySQL username
password="your_password" # Replace with your MySQL password
# Create database and table
def create_database_and_table():
conn = connect_to_mysql()
cursor = conn.cursor()
# Create database and table
cursor.execute("CREATE DATABASE IF NOT EXISTS Company")
cursor.execute("USE Company")
cursor.execute("""
CREATE TABLE IF NOT EXISTS Client (
C_ID INT PRIMARY KEY,
ClientName VARCHAR(100),
City VARCHAR(50)
""")
# Sample data
clients = [
(1, 'Alice', 'Delhi'),
(2, 'Bob', 'Mumbai'),
(3, 'Charlie', 'Delhi'),
(4, 'David', 'Bangalore'),
(5, 'Eva', 'Delhi')
cursor.executemany("INSERT INTO Client VALUES (%s, %s, %s)", clients)
conn.commit() # Save changes
print("Database and table created, sample records inserted.")
conn.close() # Close connection
# Read and display records from the table where city is 'Delhi'
def display_clients_in_delhi():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("SELECT * FROM Client WHERE City = 'Delhi'")
print("Clients in Delhi:")
for row in cursor.fetchall():
print(row)
conn.close() # Close connection
# Delete client record based on C_ID
def delete_client(c_id):
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("DELETE FROM Client WHERE C_ID = %s", (c_id,))
conn.commit() # Save changes
print("Client record deleted.")
conn.close() # Close connection
# Display all records from the Client table
def display_all_clients():
conn = connect_to_mysql()
cursor = conn.cursor()
cursor.execute("USE Company")
cursor.execute("SELECT * FROM Client")
print("All Clients:")
for row in cursor.fetchall():
print(row)
conn.close() # Close connection
# Menu-driven program
def main():
while True:
print("\n1. Create Database and Table")
print("2. Display Clients in Delhi")
print("3. Delete Client by C_ID")
print("4. Display All Clients")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_database_and_table()
elif choice == '2':
display_clients_in_delhi()
elif choice == '3':
c_id = int(input("Enter Client ID to delete: "))
delete_client(c_id)
elif choice == '4':
display_all_clients()
elif choice == '5':
break
else:
print("Invalid choice, try again.")
main()