0% found this document useful (0 votes)
3 views

pythonlab8

The document outlines a series of Python programs that demonstrate file processing, error handling, and exception management. It includes tasks such as counting words in a file, finding and replacing text, managing student records, and performing division with error handling. Each program is accompanied by code snippets and descriptions of their functionality and expected outputs.

Uploaded by

Athish Vishnu
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)
3 views

pythonlab8

The document outlines a series of Python programs that demonstrate file processing, error handling, and exception management. It includes tasks such as counting words in a file, finding and replacing text, managing student records, and performing division with error handling. Each program is accompanied by code snippets and descriptions of their functionality and expected outputs.

Uploaded by

Athish Vishnu
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/ 7

EX.

NO: 8
71762305009 FILES, ERRORS AND EXCEPTIONS
12.03.2025

AIM:

To implement python program using files, errors and exceptions.

PROGRAM:

1. File Processing and Word Count


Write a Python program that:
 Reads a text file (data.txt).
 Counts the number of words in the file.
 Displays the word count.
 Handles the case where the file does not exist.

CODE:

s=input("enter the file name:")


try:
f=open(f"{s}.txt","r")
c=f.read()
cnt=0
for x in c:
if x==" ":
cnt+=1
print(f"No of words:{cnt}")

except FileNotFoundError:
print("No such file exist")

OUTPUT:

2. Find and Replace in a File


Write a Python program that:
 Reads a file (sample.txt).
 Asks the user for a word to find and a word to replace it with.
 Writes the modified content to a new file (updated_sample.txt).
 Ensure the original file remains unchanged.
CODE:
r="Padmesh"
re="Athish"
f=open("Hardwork.txt","r")
c=f.read()
print("CONTENT IN Hardwork:")
print(f"{c}")
f.close()
f2=open("Hardwork2.txt","w+")
a=c.replace(r,re)
f2.write(a)
f2.close()
f2=open("Hardwork2.txt","r")
print("CONTENT IN Hardwork2:")
d=f2.read()
print(f"{d}")
f2.close()

OUTPUT:

3. Write a Student Records File


Write a Python program that:
 Accepts student names and scores from the user.
 Saves the data in a file (students.txt) in this format
 Reads the file and displays the highest-scoring student.
CODE:
n=int(input("enter no of students:"))
x=n
f=open("marks.txt","w")
f.write("")
f.close()
while x>0:
f=open("marks.txt","a")
s=input("enter the name of the student:")
m=int(input("enter marks:"))
f.writelines(f"{s}-{m} \n")
f.close()
x-=1
f=open("marks.txt","r")
c=f.readlines()
print(c)
max=-1
for i in c:
if int(i[-3:-5])>max:
high=i
print("Best performance")
print(f"{high}")

OUTPUT:

4. Division Calculator with Exception Handling


Write a program that:
 Takes two numbers as input.
 Performs division.
 Handles ZeroDivisionError if the denominator is zero.
 Handles ValueError if a non-numeric value is entered.

CODE:
try:
a=int(input("enter number 1:"))
b=int(input("enter number 2:"))
c=a/b
except ValueError as e:
print("Input is non numeric")
except ZeroDivisionError:
print("Denominator is zero")
else:
print(f"{c}")

OUTPUT:

5. Open a Non-Existing File


Write a program that:
 Asks the user for a filename.
 Tries to open and read the file.
 Handles FileNotFoundError and displays a proper message.

CODE:

s=input("enter the file name:")


try:
f=open(f"{s}.txt","r")
c=f.read()
print(f"{c}")

except FileNotFoundError:
print("No such file exist")
OUTPUT:

7. Student Records Management System


You are required to develop a Python program that records student names and
their marks in a subject.
After all records are saved, read the file and display:
 The top-scoring student (highest mark).
 The average mark of the class.
 The number of students who failed (score below 50).
Errors and Exceptions to Handle
o FileNotFoundError: If the file doesn't exist
o ValueError: When converting strings to numbers fails
o Marks outside expected range (e.g., negative or >100)
o Missing entries for some students

CODE:

import csv
import os

FILE_NAME = input("enter the file name of the students marks:")

def process_records():
try:

if not os.path.exists(FILE_NAME):
raise FileNotFoundError(f"{FILE_NAME} not found!")

records = []
with open(FILE_NAME, mode="r") as file:
csv_reader = csv.reader(file)
header = next(csv_reader)

for row in csv_reader:


try:
if len(row) != 2:
raise ValueError("Incomplete record, skipping entry.")

name = row[0].strip()
mark = int(row[1].strip())

if mark < 0 or mark > 100:


raise ValueError(f"Invalid mark for {name}, skipping entry.")

records.append((name, mark))

except ValueError as e:
print(f"Skipping invalid record: {row} - {e}")

if not records:
print("No valid records found.")
return

top_student, top_mark = max(records, key=lambda x: x[1])


avg_mark = sum(mark for _, mark in records) / len(records)
failed_students = sum(1 for _, mark in records if mark < 50)

print(f"\nTop-scoring student: {top_student} with {top_mark}")


print(f"Average mark of the class: {avg_mark:.2f}")
print(f"Number of students who failed: {failed_students}")

except FileNotFoundError as e:
print(f"Error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")

def main():
while True:
print("\n1. Process and Display Records from CSV")
print("2. Exit")
choice = input("Enter your choice (1/2): ")

if choice == "1":
process_records()
elif choice == "2":
print("Exiting...")
break
else:
print("Invalid choice! Please enter 1 or 2.")

if __name__ == "__main__":
main()

OUTPUT:

RESULT:
The programs on files, errors and exceptions have been implemented and
executed successfully.

You might also like