UNIT-IV
UNIT-IV: FILES AND OBJECT-ORIENTED PROGRAMMING
1. Files: Types, Creating and Reading Text Data, File Methods to Read and Write
Data
Files are used to store data persistently outside of program memory. Python supports
different file types: text files (human-readable) and binary files (non-readable). You open
files using the open() function with modes such as 'r' (read), 'w' (write), 'a' (append), and 'b'
(binary). Reading from files can be done with .read(), .readline(), or .readlines() methods.
Writing uses .write() or .writelines(). It’s important to close files after operations using
.close() or preferably use with statement (context manager) for automatic closing. Proper file
handling prevents data loss and ensures resource management.
2. Reading and Writing Binary Files, Pickle Module, Reading and Writing CSV Files
Binary files store data in binary format and require binary mode ('rb' or 'wb') to read/write.
The pickle module serializes and deserializes Python objects to/from binary files, allowing
complex data like objects and lists to be saved and loaded. CSV files (Comma Separated
Values) store tabular data; Python’s csv module provides functions to read and write CSVs
easily, handling commas, newlines, and quotes properly. These file operations are vital in
real-world applications like data storage, sharing, and interoperability with other programs.
3. Python os and os.path Modules
The os module provides portable ways to interact with the operating system, such as reading
environment variables, creating/deleting directories, and running system commands. The
os.path submodule handles file path manipulations like joining, splitting, checking existence,
and getting file metadata. These modules are essential for writing robust, OS-independent
Python scripts that interact with the filesystem.
4. Object-Oriented Programming (OOP): Classes and Objects
OOP is a programming paradigm based on the concept of objects, which encapsulate data
and behavior. In Python, classes define blueprints for objects. A class contains attributes
(variables) and methods (functions). Objects are instances of classes created by calling the
class name like a function. The __init__ method is a constructor that initializes new objects.
Understanding classes and objects is fundamental for designing modular, reusable, and
maintainable code. OOP helps model real-world entities and relationships naturally.
5. Classes with Multiple Objects, Class Attributes vs Data Attributes
Multiple objects can be created from a single class, each maintaining its own state through
instance variables. Class attributes are shared by all instances, whereas data attributes
(instance variables) belong to individual objects. Differentiating between them is crucial for
proper data handling in OOP. Class methods and static methods operate differently regarding
access to instance or class-level data.
6. Encapsulation, Inheritance, Polymorphism
Encapsulation hides object data by using private variables (conventionally prefixed
with underscores) and exposes interfaces via methods, promoting data integrity and
security.
Inheritance allows a new class (child) to inherit properties and methods from an
existing class (parent), facilitating code reuse and hierarchical organization.
Polymorphism enables methods to work with objects of different classes, typically
through method overriding or duck typing, increasing flexibility. These OOP
principles are key for advanced design and building complex applications.
SAMPLE EXPERIMENTS:
1. Sort words in a file and write to another file (lowercased)
# Writing sample data to input file
with open("input.txt", "w") as f:
f.write("Banana Apple orange Mango kiwi")
# Reading, processing, and writing to output file
with open("input.txt", "r") as f:
words = f.read().lower().split()
words.sort()
with open("output.txt", "w") as f:
for word in words:
f.write(word + "\n")
# Output: Words sorted and written in lower-case to output.txt
2. Print each line of a file in reverse order
with open("sample.txt", "w") as f:
f.write("Hello world\nPython is fun\nOpenAI GPT")
with open("sample.txt", "r") as f:
lines = f.readlines()
for line in lines:
print(line.strip()[::-1])
Output:
dlrow olleH
nuf si nohtyP
TPG IAnepO
3. Compute number of characters, words, and lines in a file
with open("sample.txt", "r") as f:
lines = f.readlines()
num_lines = len(lines)
num_words = sum(len(line.split()) for line in lines)
num_chars = sum(len(line) for line in lines)
print("Lines:", num_lines)
print("Words:", num_words)
print("Characters:", num_chars)
Output:
assume the sample.txt is
Hello world.
This is a test file.
Python is great!
Lines: 3
Words: 10
Characters: 54
4. Create, display, append, insert, and reverse an array
import array
arr = array.array('i', [10, 20, 30])
# Display
print("Original array:", arr)
# Append
arr.append(40)
print("After append:", arr)
# Insert at position
arr.insert(1, 15)
print("After insert at index 1:", arr)
# Reverse
arr.reverse()
print("Reversed array:", arr)
Output:
Original array: array('i', [10, 20, 30])
After append: array('i', [10, 20, 30, 40])
After insert at index 1: array('i', [10, 15, 20, 30, 40])
Reversed array: array('i', [40, 30, 20, 15, 10])
5. Add, transpose, and multiply two matrices
import numpy as np
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Addition
add = A + B
print("Addition:\n", add)
# Transpose
print("Transpose of A:\n", A.T)
# Multiplication
multiply = A @ B
print("Multiplication:\n", multiply)
Output:
Addition:
[[ 6 8]
[10 12]]
Transpose of A:
[[1 3]
[2 4]]
Multiplication:
[[19 22]
[43 50]]
6. Class representing shapes with subclasses
import math
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius**2
def perimeter(self):
return 2 * math.pi * self.radius
class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def perimeter(self):
return self.a + self.b + self.c
def area(self):
s = self.perimeter() / 2
return math.sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side**2
def perimeter(self):
return 4 * self.side
# Example usage
circle = Circle(5)
print("Circle - Area:", circle.area(), "Perimeter:", circle.perimeter())triangle = Triangle(3, 4,
5)
print("Triangle - Area:", triangle.area(), "Perimeter:", triangle.perimeter())
square = Square(4)
print("Square - Area:", square.area(), "Perimeter:", square.perimeter())
Output:
Circle - Area: 78.53981633974483 Perimeter: 31.41592653589793
Triangle - Area: 6.0 Perimeter: 12
Square - Area: 16 Perimeter: 16