Python File Handling
Python File Handling
PROGRAMMING
CHAPTER - IV
FILE HANDLING ,CLASSES AND
OBJECTS
MCA - I SEM
Prepared By:
[Link]
Lecturer of BCA
&MCA
Oxford college,
Hubli
2024-2025
1
File handling
File handling in Python involves interacting with files on your computer to read data from
them or write data to them.
Python provides several built-in functions and methods for creating, opening, reading,
writing, and closing files.
Output:
Hello, this is a test file.
Python file handling is easy!
2
Reading a File in Python
Reading a file in Python involves opening the file in a mode that allows for reading, and then
using various methods to extract the data from the file. Python provides several methods to read
data from a file −
read() − Reads the entire file.
To read a file, you need to open it in read mode. The default mode for the open() function is read
mode ('r'), but it's good practice to specify it explicitly.
Example :
# Open the file in read mode
try:
with open('[Link]', 'r') as file:
# Read the entire content of the file
content = [Link]()
print("File content:\n")
print(content)
except FileNotFoundError:
print("The file does not exist.")
Output :
File content:
3
Output:
Content added Successfully!!
Output:
Content added Successfully!!
Example :
# Writing binary data to a file
data = bytes([120, 3, 255, 0, 100]) # Binary data
with open('[Link]', 'wb') as file:
[Link](data)
Note:
'rb': Read mode for binary files (reads in binary).
When you open a binary file, you read and write raw bytes, not characters.
import csv
# Reading from a CSV file
with open('[Link]', 'r') as file:
reader = [Link](file)
for row in reader:
print(row) # Each row is a list of values
4
writer = [Link](file)
[Link](data) # Write multiple rows
Example
In this example, we open the file for writing, write data to the file, and then close the file using
the close() method −
Output:
File closed successfully!!
Example
In this example, the file is automatically closed at the end of the with block, so there is no
need to call close() method explicitly −
Output:
File closed successfully!!
5
try:
file = open("[Link]", "w")
[Link]("This is an example with exception handling.")
finally:
[Link]()
print ("File closed successfully!!")
Output:
File closed successfully!!
Here's a list of file handling modes in Python along with a brief description:
6
Python Classes and Objects
We know that Python also supports the concept of objects and classes.
An object is simply a collection of data (variables) and methods (functions).
A class is a blueprint for that object and an object is an instance of a class.
we can create many objects from a class.
Class
A class is a template or blueprint for creating objects (instances). It defines the attributes
(variables) and methods (functions) that objects of the class will have.
__init_(_): This is a special method called a constructor that initializes objects of the
class. It's called when an object is created.
self: A reference to the current instance of the class. It is used to access the object's
attributes and methods.
Syntax :
class ClassName:
def __init__(self, attribute1, attribute2):
self.attribute1 = attribute1
self.attribute2 = attribute2
def method_name(self):
# Some operation or functionality
pass
Example :
class Car:
def __init__(self, make, model, year):
[Link] = make
[Link] = model
[Link] = year
def display_info(self):
print(f"{[Link]} {[Link]} {[Link]}")
Output:
2020 Toyota Corolla
Object:
An object is an instance of a class. When you create an object, you're using the class as a
blueprint to allocate memory and set initial values for the object's attributes.
Syntax :
object_name = ClassName(arguments)
7
Key concepts:
Attributes: These are the variables associated with an object.
In the above example: make, model, and year are attributes of the Car class.
Methods: These are functions defined inside a class that describe the behaviors of the
objects. In the above example, display_info is a method that displays
information about the car.
Example:
# Define a class called 'Car'
class Car:
def __init__(self, make, model, year):
# Initialize attributes of the class
[Link] = make
[Link] = model
[Link] = year
Output:
2020 Toyota Corolla
2021 Honda Civic
def drive(self):
print("The car is now driving.")
Output:
Engine started.
The car is now driving.
8
2: Calling a method from another class
class Light:
def turn_on(self):
print("The light is turned on.")
def turn_off(self):
print("The light is turned off.")
class Room:
def __init__(self):
[Link] = Light() # Room has a Light object as an attribute
def enter_room(self):
print("Entering the room...")
[Link].turn_on() # Calling the turn_on method of the Light class
def leave_room(self):
print("Leaving the room...")
[Link].turn_off() # Calling the turn_off method of the Light class
Output:
Entering the room...
The light is turned on.
Leaving the room...
The light is turned off.
Abstract Class:
The classes that cannot be instantiated. This means that we cannot create objects of an
abstract class and these are only meant to be inherited. Then an object of the derived class
is used to access the features of the base class. These are specifically defined to lay a
foundation of other classes that exhibit common behavior or characteristics.
The abstract class is an interface. Interfaces in OOP enable a class to inherit data and
functions from a base class by extending it.
In Python, we use the NotImplementedError to restrict the instantiation of a class. Any
class having this error inside method definitions cannot be instantiated.
Abstract Method: An abstract method is a method that is declared in the abstract class
but does not have a body or implementation. Subclasses must implement this method.
9
Syntax to implement data abstaction:
Example:
from abc import ABC, abstractmethod
import math
# Abstract class
class Shape(ABC):
@abstractmethod
def area(self):
pass
def area(self):
return [Link] * ([Link] ** 2)
def area(self):
return [Link] * [Link]
10
# Creating objects of concrete classes
circle = Circle(5)
rectangle = Rectangle(4, 6)
Output:
Area of Circle: 78.53981633974483
Area of Rectangle: 24
Example :
class BankAccount:
def __init__(self, owner, balance):
self.__owner = owner # Private attribute
self.__balance = balance # Private attribute
11
# Public method to deposit money (setter)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited {amount}. New balance: {self.__balance}")
else:
print("Invalid deposit amount.")
Output:
Initial Balance: 1000
Deposited 500. New balance: 1500
Withdrew 200. New balance: 1300
Data members :
In Python, data members (also known as attributes) are variables that belong to a class and are
used to store data for instances of that class. These data members can either be instance
variables or class variables depending on their scope and usage.
12
Class methods and static methods
In Python, class methods and static methods are types of methods that are defined within a class,
but they behave differently from regular instance methods.
Class Methods
Class methods are methods that are bound to the class rather than its objects. They can
access and modify class-level variables.
Class methods take a special first argument called cls, which refers to the class itself (not an
instance of the class).
To define a class method, you use the @classmethod decorator.
Example :
class Dog:
species = "Canis familiaris" # Class variable
@classmethod
def change_species(cls, new_species):
[Link] = new_species # Modify the class variable
@classmethod
def print_species(cls):
print(f"Species: {[Link]}")
dog1 = Dog("Buddy")
dog2 = Dog("Bella")
# Verifying that both dog1 and dog2 share the same class-level variable value
Output:
Species: Canis lupus familiaris
Species: Canis lupus familiaris
Note:
In this above example ,change_species is a class method that modifies the class-level variable
[Link] dog1 and dog2 share the modified species variable.
13
Static Methods
Static methods do not operate on the class or instance. They don't have access to self or cls.
They are just functions that belong to the class namespace.
Static methods are defined using the @staticmethod decorator.
Static methods are used when you need a function that logically belongs to the class but
does not need to access or modify the class or instance.
Example :
class Math:
@staticmethod
def add(x, y):
return x + y
@staticmethod
def multiply(x, y):
return x * y
Output:
8
28
Note:
In this above example , add and multiply are static methods because they don’t require access to
either the class or instance. They just perform a computation.
Key Differences:
Feature Instance Method Class Method Static Method
First
self (refers to Instance) cls (refers to the class) None (doesn’t take self or cls)
argument
Class variables and Neither instance nor class
Accesses Instance variables and methods
methods variables, just data
Works on class-level Utility functions that don't
Use case Works on instance-level data
data depend on instance or class
Decorator None (just a normal method) @classmethod @staticmethod
When you need to When you need a utility
When you need to operate on operate on class-level function that logically belongs
When to
data that is specific to a data or when you want to the class but does not
use each
particular object (instance). to modify class-level need access to any class or
class
variables, or use the instance-specific data.
class as a factory
method.
14
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) in Python,
allowing one class (the subclass or child class) to inherit attributes and methods from
another class (the superclass or parent class).
It is used to inherit the properties and behaviours of one class to another.
The class that inherits another class is called a child class and the class that gets inherited is
called a base class or parent class.
This enables code reuse and can help structure programs in a more modular and organized
way.
Benefits of Inheritance:
Code Reusability: We can reuse the code in the parent class without rewriting it in the child
class.
Extensibility: We can easily extend the functionality of the parent class by adding new
methods or modifying existing ones in the child class.
Syntax
class ParentClassName:
{class body}
Syntax
class SubClassName (ParentClass1[, ParentClass2, ...]):
{sub class body}
Types of Inheritance
In Python, inheritance can be divided in five different categories −
Single Inheritance
Multiple Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid inheritance
15
Single Inheritance
This is the simplest form of inheritance where a child class inherits attributes and methods from
only one parent class.
Syntax :
# Parent Class (Super class)
class ParentClass:
# statements
Example :
# Parent class (Super class)
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
return f"{[Link]} makes a sound."
Output:
Buddy says Woof!
Multiple Inheritance
Multiple inheritance in Python allows you to construct a class based on more than one
parent classes.
The Child class thus inherits the attributes and method from all parents. The child can
override methods inherited from any parent.
Syntax :
class parent1:
#statements
class parent2:
#statements
16
Method Resolution Order (MRO)
The term method resolution order is related to multiple inheritance in Python. In Python, inheritance
may be spread over more than one levels. Let us say A is the parent of B, and B the parent for C. The
class C can override the inherited method or its object may invoke it as defined in its parent. So, how
does Python find the appropriate method to call.
Each Python has a mro() method that returns the hierarchical order that Python uses to resolve the
method to be called. The resolution order is from bottom of inheritance order to top.
Multilevel Inheritance
In multilevel inheritance, a class is derived from another derived class. There exists multiple layers of
inheritance. We can imagine it as a grandparent-parent-child relationship.
Syntax :
# Parent Class (Super class)
class GrandparentClass:
# statements
Example :
# parent class
class Universe:
def universeMethod(self):
print ("I am in the Universe")
# child class
class Earth(Universe):
def earthMethod(self):
print ("I am on Earth")
# creating instance
person = India()
# method calls
[Link]()
[Link]()
[Link]()
Output :
I am in the Universe
I am on Earth
I am in India
17
Hierarchical Inheritance
This type of inheritance contains multiple derived classes that are inherited from a single base class.
This is similar to the hierarchy within an organization.
Syntax :
# Parent Class (Super class)
class ParentClass:
# statements
Example :
# parent class
class Manager:
def managerMethod(self):
print ("I am the Manager")
# child class
class Employee1(Manager):
def employee1Method(self):
print ("I am Employee one")
# creating instances
emp1 = Employee1()
emp2 = Employee2()
# method calls
[Link]()
emp1.employee1Method()
[Link]()
emp2.employee2Method()
Output :
I am the Manager
I am Employee one
I am the Manager
I am Employee two
18
Hybrid Inheritance
Combination of two or more types of inheritance is called as Hybrid Inheritance. For instance, it could
be a mix of single and multiple inheritance.
Syntax :
# Parent Class 1 (Super class)
class ClassA:
# statements
# Parent Class 2 (Super class)
class ClassB:
# statements
Example :
# parent class
class ParentDemo:
def __init__(self, msg):
[Link] = msg
def showMessage(self):
print([Link])
# child class
class ChildDemo(ParentDemo):
def __init__(self, msg):
# use of super function
super().__init__(msg)
# creating instance
obj = ChildDemo("Welcome to Python!!")
[Link]()
Output :
Welcome to Python!!
19
Python - Interfaces
In software engineering, an interface is a software architectural pattern. It is similar to a class but
its methods just have prototype signature definition without any executable code or
implementation body. The required functionality must be implemented by the methods of any
class that inherits the interface.
In languages like Java and other, there is keyword called interface which is used to define an
interface , But Python doesn't have it or any similar keyword. It uses abstract base classes (in
short ABC module) and @abstractmethod decorator to create interfaces.
An abstract class and interface appear similar in Python. The only difference in two is that the
abstract class may have some non-abstract methods, while all methods in interface must be
abstract, and the implementing class must override all the abstract methods.
Formal Interface
Formal interfaces in Python are implemented using abstract base class (ABC). To use this class,
you need to import it from the abc module.
Example :
from abc import ABC, abstractmethod
# creating interface
class demoInterface(ABC):
@abstractmethod
def method1(self):
print ("Abstract method1")
return
@abstractmethod
def method2(self):
print ("Abstract method1")
return
20
# creating instance
obj = concreteclass()
# method call
obj.method1()
obj.method2()
Output:
This is method1
This is method2
Informal Interface
In Python, the informal interface refers to a class with methods that can be overridden. However,
the compiler cannot strictly enforce the implementation of all the provided methods.
This type of interface works on the principle of duck typing. It allows us to call any method on an
object without checking its type, as long as the method exists.
Example:
class demoInterface:
def displayMsg(self):
pass
class newClass(demoInterface):
def displayMsg(self):
print ("This is my message")
# creating instance
obj = newClass()
# method call
[Link]()
Output :
This is my message
Unlike other programming languages like Java, C++, and C#, Python does not support the
feature of method overloading by default. However, there are alternative ways to achieve it.
If you define a method multiple times,the last definition will override the previous ones.
Therefore, this way of achieving method overloading in Python generates error.
To simulate method overloading, we can use a workaround by defining default value to method
arguments as None, so that it can be used with one, two or three arguments.
21
Example :
class example:
def add(self, a = None, b = None, c = None):
x=0
if a !=None and b != None and c != None:
x = a+b+c
elif a !=None and b != None and c == None:
x = a+b
return x
obj = example()
print ([Link](10,20,30))
print ([Link](10,20))
Output :
60
30
First, you need to install the Multipledispatch module using the following command −
pip install multipledispatch
This module has a @dispatch decorator. It takes the number of arguments to be passed to the
method to be overloaded. Define multiple copies of add() method with @dispatch decorator as
below −
Example :
from multipledispatch import dispatch
class example:
@dispatch(int, int)
def add(self, a, b):
x = a+b
return x
@dispatch(int, int, int)
def add(self, a, b, c):
x = a+b+c
return x
obj = example()
print ([Link](10,20,30))
print ([Link](10,20))
Output:
60
30
22
Python - Method Overriding
The Python method overriding refers to defining a method in a subclass with the same name as a
method in its superclass. In this case, the Python interpreter determines which method to call at
runtime based on the actual object being referred to.
You can always override your parent class methods. One reason for overriding parent's methods
is that you may want special or different functionality in your subclass.
Example :
In the code below, we are overriding a method named myMethod of Parent class.
# define parent class
class Parent:
def myMethod(self):
print ('Calling parent method')
# instance of child
c = Child()
# child calls overridden method
[Link]()
Output :
Calling child method
__del__( self )
2 Destructor, deletes an object
Sample Call : del obj
__repr__( self )
3 Evaluatable string representation
Sample Call : repr(obj)
__str__( self )
4 Printable string representation
Sample Call : str(obj)
23