Chapter 4: File Handling, OOP and Mini Project
MODULE 1 | WEEK 4
Chapter 4: File Handling, OOP and Mini Project
In this last chapter we will learn three things: File Handling (reading and writing files), Object-Oriented Programming (OOP) (building code in the form of objects), and then we will join all of it together into a Mini Project .
4.1 File Handling
Until now our data lived in memory only while the program was running. When the program closed, the data was gone. With File Handling we save data in a file and can read it back later.
File modes
| Mode | Meaning | KEEP IN MIND |
|---|---|---|
| "r" | Read (reading only) | Error if the file does not exist. This is the default. |
| "w" | Write | Creates the file if it does not exist.Erases the old content! |
| "a" | Append (add at the end) | The old content stays. |
| "r+" | Both read and write | The file must already exist. |
| "x" | Create a new file | Error if the file already exists. |
The with Statement (the best way)
with closes the file by itself after the work, even if an error occurs in between. Always use this.
# Writing to a file
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("First line\n")
f.write("Second line\n")
# Reading a file (the whole file as one string)
with open("notes.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
Three Ways of Reading
# read() -> the whole file as one string
# readline() -> one line
# readlines() -> a list of all the lines
with open("notes.txt", "r", encoding="utf-8") as f:
first = f.readline()
print("First:", first.strip())
with open("notes.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
print(lines) # ['First line\n', 'Second line\n']
# Best for big files: loop line by line
with open("notes.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())
Ways of Writing, and Append
with open("notes.txt", "a", encoding="utf-8") as f: # append
f.write("Third line\n")
names = ["Ali\n", "Sara\n", "Hina\n"]
with open("names.txt", "w", encoding="utf-8") as f:
f.writelines(names) # write all the lines of the list
with open("names.txt") as f:
print(f.read())
4.2 Exception Handling (how to deal with errors)
This topic is not listed separately in the syllabus, but it is needed along with file handling (for example, what if the file does not exist?). An exception is an error that occurs while the program is running. With try / except we can stop the program from crashing.
try:
num = int("abc") # a ValueError will occur
print(10 / num)
except ValueError:
print("This is not a number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("No error occurred")
finally:
print("This always runs")
try:
with open("does_not_exist.txt") as f:
print(f.read())
except FileNotFoundError:
print("File not found!")
| Error | When it occurs |
|---|---|
| ValueError | The type of the value is fine but the value is wrong (int("abc")) |
| TypeError | An operation on the wrong type ("5" + 5) |
| ZeroDivisionError | Division by zero (10 / 0) |
| IndexError | The list index does not exist ([1,2][5]) |
| KeyError | The key does not exist in the dictionary |
| FileNotFoundError | The file was not found |
| NameError | The variable name was never defined |
4.3 CSV and JSON Files (essential for Data Science)
In Data Science, data is often in CSV or JSON files. For now just understand the basics; in Module 2 this becomes very easy with Pandas.
-
CSV (Comma Separated Values): table-like data, each value separated by a comma. It opens in Excel.
-
JSON: data shaped like a dictionary, common in websites and apps.
import csv, json
# Writing CSV
rows = [["name", "marks"], ["Ali", 85], ["Sara", 92]]
with open("students.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
# Reading CSV
with open("students.csv", encoding="utf-8") as f:
for row in csv.reader(f):
print(row)
# Writing and reading JSON
data = {"name": "Ali", "marks": [85, 90]}
with open("data.json", "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
with open("data.json", encoding="utf-8") as f:
loaded = json.load(f)
print(loaded["marks"])
4.4 Object-Oriented Programming (OOP)
So far our code has been made of functions and variables . As programs get bigger they become hard to manage. In OOP we think of programs in the form of objects , the way things are in the real world: Student, Car, BankAccount.
Class and Object
-
Class: the blueprint for making objects. In it we say what the object will have (attributes) and what it will be able to do (methods).
-
Object (Instance): the actual thing made from a class.
-
Attribute: a characteristic (data) of the object, such as name, age.
-
Method: an action (function) of the object, such as speaking, calculating.
-
init: a special method that runs by itself as soon as an object is created (the constructor). The attributes are set in it.
-
self: tells which object the work is being done on ("myself").
class Student:
school = "NED" # class attribute (shared by all students)
def __init__(self, name, marks): # constructor
self.name = name # instance attributes
self.marks = marks
def introduce(self): # method
print(f"My name is {self.name}, marks {self.marks}")
def is_pass(self):
return self.marks >= 40
s1 = Student("Ali", 85) # created an object
s2 = Student("Sara", 35)
s1.introduce()
print(s2.is_pass()) # False
print(s1.school, s2.school)
str (how an object is printed)
class Book:
def __init__(self, title, price):
self.title = title
self.price = price
def __str__(self):
return f"{self.title} (Rs. {self.price})"
b = Book("Python Basics", 500)
print(b) # Python Basics (Rs. 500)
The 4 Basic Pillars of OOP
1) Encapsulation (protecting data)
Bundling the data and the methods that work on it together in one class , and preventing the data from being changed directly. In Python _name (one underscore) means "internal, do not touch", and __name (two underscores) hides it further.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance # private (hidden)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
def withdraw(self, amount):
if amount <= self.__balance:
self.__balance -= amount
else:
print("Not enough balance!")
def get_balance(self):
return self.__balance
acc = BankAccount("Ali", 1000)
acc.deposit(500)
acc.withdraw(2000) # Not enough balance!
print(acc.get_balance()) # 1500
# print(acc.__balance) # ERROR: cannot be accessed directly
2) Inheritance
One class (the child ) takes on the features of another class (the parent ), and can also add its own new things. This saves us from rewriting code.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def intro(self):
print(f"I am {self.name}, age {self.age}")
class Teacher(Person): # inherits from Person
def __init__(self, name, age, subject):
super().__init__(name, age) # run the parent's __init__
self.subject = subject
def teach(self):
print(f"{self.name} teaches {self.subject}")
t = Teacher("Sana", 30, "Python")
t.intro() # a method inherited from Person
t.teach()
Method Overriding: a child class can rewrite a parent's method in its own way.
3) Polymorphism (one name, many forms)
A method with the same name works in its own way on different objects.
class Animal:
def speak(self):
print("Some sound")
class Cat(Animal):
def speak(self): # overriding
print("Meow")
class Dog(Animal):
def speak(self):
print("Woof")
for pet in [Cat(), Dog(), Animal()]:
pet.speak() # Meow, Woof, Some sound
4) Abstraction (showing only what is necessary)
Hiding the inner complexity and showing only the necessary interface. In Python, the abc module lets us make an abstract class , in which a method has only a name and the child classes are obliged to complete it.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self): # only the name, no body
pass
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14159 * self.r ** 2
shapes = [Rectangle(4, 5), Circle(3)]
for s in shapes:
print(round(s.area(), 2)) # 20 and 28.27
# Shape() # ERROR: an object of an abstract class cannot be
made
COMMON MISTAKES
-
Opening a file in "w" mode when you want to keep the old content. "w" erases everything old; use "a" .
-
Writing open() and forgetting close() instead of using with .
-
Forgetting to write self as the first parameter of a method.
-
Writing an attribute inside a class without self. (writing just name = name ).
-
Forgetting super().init() in a child class.
-
Treating a class and an object as the same thing. The class is the blueprint, the object is the actual house.
4.5 Mini Project: Student Record Manager
Now we bring together everything from Week 1 to 4 in one place. This is a console program that adds students' records, shows them, searches them, and saves them in a JSON file (so the data survives even after the program closes).
What will be used in this project
-
OOP: the Student class and the StudentManager class
-
File handling: saving and loading with a JSON file
-
Exception handling: the program should not crash if the file is missing or the input is wrong
-
Data structures: list and dictionary
-
Control flow: a menu with a while loop and if / elif / else
-
Functions and strings
Step 1: Student class
class Student:
def __init__(self, roll_no, name, marks):
self.roll_no = roll_no
self.name = name
self.marks = marks
def to_dict(self): # for saving to a file
return {"roll_no": self.roll_no, "name": self.name,
"marks": self.marks}
def __str__(self):
return f"[{self.roll_no}] {self.name} - {self.marks} marks"
Step 2: The StudentManager class (full code)
import json
class Student:
def __init__(self, roll_no, name, marks):
self.roll_no = roll_no
self.name = name
self.marks = marks
def to_dict(self):
return {"roll_no": self.roll_no, "name": self.name,
"marks": self.marks}
def __str__(self):
return f"[{self.roll_no}] {self.name} - {self.marks} marks"
class StudentManager:
def __init__(self, filename="students.json"):
self.filename = filename
self.students = []
self.load()
def load(self):
try:
with open(self.filename, "r", encoding="utf-8") as f:
for d in json.load(f):
self.students.append(
Student(d["roll_no"], d["name"], d["marks"]))
except FileNotFoundError:
self.students = [] # the file will not exist the first time
def save(self):
data = [s.to_dict() for s in self.students]
with open(self.filename, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
def add(self, roll_no, name, marks):
for s in self.students:
if s.roll_no == roll_no:
print("This roll number already exists!")
return
self.students.append(Student(roll_no, name, marks))
self.save()
print("Student added.")
def show_all(self):
if not self.students:
print("No records.")
for s in self.students:
print(s)
def search(self, name):
found = [s for s in self.students
if name.lower() in s.name.lower()]
for s in found:
print(s)
if not found:
print("Not found.")
def average(self):
if not self.students:
return 0
return sum(s.marks for s in self.students) / len(self.students)
def main():
manager = StudentManager()
while True:
print("\n1. Add 2. Show all 3. Search 4. Average 5. Exit")
choice = input("Choice: ")
if choice == "1":
try:
roll = int(input("Roll no: "))
name = input("Name: ")
marks = float(input("Marks: "))
manager.add(roll, name, marks)
except ValueError:
print("Roll no and marks must be numbers!")
elif choice == "2":
manager.show_all()
elif choice == "3":
manager.search(input("Enter name: "))
elif choice == "4":
print("Average marks:", round(manager.average(), 2))
elif choice == "5":
print("Goodbye!")
break
else:
print("Wrong choice!")
# To run in Colab / Python:
# main()
Step 3: Run it and test it
-
Paste the whole code into one cell and remove the # from the last main() line.
-
Run the cell. The menu will appear.
-
Add 3 students with option 1.
-
See them with option 2, search by name with option 3, see the average with option 4.
-
Exit with option 5, then run the cell again. The old data will come back, because it was saved in the JSON file.
Extensions (make the project your own)
-
An option to delete or edit a student.
-
A list sorted by marks (top students).
-
A method to work out the grade (A, B, C).
-
A check on the marks range (nothing outside 0 to 100).
-
Upload this project to GitHub along with a README.
KEY TAKEAWAYS
-
with open() closes the file by itself. Modes: r (read), w (write, erase the old), a (add at the end).
-
try / except stops the program from crashing on errors.
-
CSV is table-like data, JSON is dictionary-like data. Both are common in Data Science.
-
A class is the blueprint, an object is the actual thing. init runs as soon as the object is created, self is the object itself.
-
The 4 pillars of OOP: Encapsulation, Inheritance, Polymorphism, Abstraction.
-
In the mini project we used all the topics of Module 1 together.