0% found this document useful (0 votes)
7 views8 pages

Exp 4

Uploaded by

Senthur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views8 pages

Exp 4

Uploaded by

Senthur
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

CLASSES & OBJECTS, FILE HANDLING WITH EXCEPTIONS

Exp.no: 04
Date:

Aim:
To write python programs for understand classes and objects concepts and file
handling with exception in python.

Program:

1. Design a Python class called Student to represent student information. The class
should have attributes name , roll_number , and grade . Implement methods to add a new
student, display all student information, and search for a student by roll number.
Additionally, implement file handling to save student data to a file named "students.txt"
and handle exceptions appropriately. If the file does not exist, create it. If any file-related
errors occur during reading or writing, display an error message.

Code:
class student:
def __init__(s,name,roll,grade):
s.name=name
s.roll=roll
s.grade=grade
def add(s):
try:
fp=open("std1.txt","r")
fp.write(f" NAME:{s.name}/{s.roll}/GRADE:{(s.grade)}\n")
fp.close()
except:
fp=open("std.txt","a")
fp.write(f" NAME:{s.name}/ROLLNO:{s.roll}/GRADE:{(s.grade)}\n")
fp.close()
def sear(s):
fp=open("std.txt","r")
s.roll=input("enter roll number :")
for i in fp.readlines():
if i.split("/")[1] == s.roll:
print(i)
fp.close()
a=int(input("click 1 for add student information\nclick 2 for search student info:"))
if a==1:
num=int (input("enter no fo students info to be added" ))
for i in range(0,num):
name=str(input("enter name:"))
roll=input("enter roll no:")
grade=input("enter grade:")
s1=student(name,roll,grade)
s1.add()
elif a==2:
s1=student("","","")
s1.sear()

Output:
2. Design a Python program to track inventory in a warehouse. Create a class
called InventoryItem with attributes product_name , quantity , and price . Implement methods to
add new items to the inventory, update quantities, and display inventory details. Use file
handling to store inventory data in a file named "inventory.txt". Handle exceptions such
as invalid input or file-related errors.

Code:
class inventory:
def __init__(s,product_name,quality,price):
s.product_name=product_name
s.quality=quality
s.price=price
def add(s):
try:
fp=open("inventory24345.txt","r")
fp.write(f"{s.product_name} ")
fp.write(f"{s.quality} ")
fp.write(f"Rs{s.price}")
fp.write("\n")
fp.close()
except:
Exception as e:
fp=open("inventory.txt","a")
fp.write(f"{s.product_name} ")
fp.write(f"{s.quality} ")
fp.write(f"Rs{s.price}")
fp.write("\n")
fp.close()
def print1(s):
f=open("inventory.txt","r")
print(f.read())
f.close()
a=int(input("click 1 for add new items \nclick 2 for item info:"))
if a==1:
num=int (input("enter no fo products to be added" ))
for i in range(0,num):
print("product no :",i+1)
name=str(input("enter name of product:"))
quality=input("enter quality:")
price=input("enter price:")
s1=inventory(name,quality,price)
s1.add()
elif a==2:
s=inventory("","","")
s.print1()

Output:

3. Write a Python script to manage a simple library system. Define a class


called Book with attributes title , author , and isbn . Implement methods to add new books to
the library, search for books by title or author, and display all available books. Use file
handling to store book data in a file named "library_books.txt". Handle exceptions such
as book not found or file-related errors.

Code:
class book:
def __init__(s,book,author,isbn):
s.book=book
s.author=author
s.isbn=isbn
def add(s):
fp=open("library.txt","a")
fp.write(f"BOOK:{s.book}__AUTHOR:{s.author}__ISB NUMBER:{s.isbn}\n")
fp.close()
def display(s):
fp=open("library.txt","r")
s.book=input("enter book name :")
for i in fp.readlines():
if i.split("__")[0] == "BOOK:"+s.book:
print(i)
fp.close()
a=int(input("enter 1 for add book details \nenter 2 for view details of books:"))
if a==1:
num=int(input("enter no of books to be added:"))
for i in range (0,num):
name=input("enter name of book:")
author=input("enter author name:")
isbn=input("enter ISB number:")
s1=book(name,author,isbn)
s1.add()
if a==2:
s1=book("","","")
s1.display()

Output:
4. Create a Python program to simulate a simple banking system. Define a class
called BankAccount with attributes account_number , account_holder_name , and balance .
Implement methods to deposit money, withdraw money, and display the account details.
Use file handling to store multiple bank accounts in a file named "bank_accounts.txt".
Handle exceptions such as insufficient balance during withdrawals and file-related
errors

Code:
class bankacc:
def __init__(s,name,num,bal):
s.name=name
s.num=num
s.bal=bal
def add(s):
fp=open("bank_accounts.txt","a")
fp.write(f"NAME:{s.name}__ACCOUNT NUMBER:{s.num}__BALANCE:{s.bal}")
fp.close()
def withdrawl(s):
fp=open("bank_accounts.txt","r+")
for i in fp.readlines():
try:
if i.split("__")[1] == "ACCOUNT NUMBER:"+s.num:
temp=i.split(":")[3]
temp2=int(temp)
fp.seek(fp.tell()-len(temp),0)
print(temp2-s.bal)
if
fp.write(str(temp2-s.bal))
except:
print("no sufficient amount")
fp.close()
def deposit(s):
fp=open("bank_accounts.txt","r+")
for i in fp.readlines():
if i.split("__")[1] == "ACCOUNT NUMBER:"+s.num:
temp=i.split(":")[3]
temp2=int(temp)
fp.seek(fp.tell()-len(temp),0)
print(temp2+s.bal)
fp.write(str(temp2+s.bal))
fp.close()
a=int(input("enter 1 for add account details\nenter 2 for withdrawl\nenter 3 for deposit
mony:"))
if a== 1:
name=input("enter account name:")
num=input("enter account number:")
bal=int(input("enter account balance:"))
s1=bankacc(name,num,bal)
s1.add()
if a==2:
num=input("enter account number:")
bal=int(input("enter withdrawl amount:"))
s1=bankacc("",num,bal)
s1.withdrawl()
if a==3:
num=input("enter account number:")
bal=int(input("enter deposit amount:"))
s1=bankacc("",num,bal)
s1.deposit()
Output:

5.Write a python program to search input book name from the library file created using
files handling.

Code:
def search_book(libfile, sear):
with open("library.txt", 'r') as file:books = file.readlines()
match_book = [] for book in books:

if sear.lower() in book.lower():
match_book.append(book.strip()

return match_book
libfile = 'library.txt'
sear = input("Enter a book : ")
match_book = search_book(libfile, sear)
if match_book:
print("Matching books found:")
for book in match_book:
print(book)
else:
print("No books found.")

Output:

Result:

The above programs are executed successfully.

You might also like