0% found this document useful (0 votes)
6 views18 pages

Python UNIT 4 New

This document covers file handling in Python, including types of files (text and binary), operations such as creating, opening, reading, writing, and closing files, as well as file paths and the format operator. It also introduces object-oriented programming concepts, including classes, objects, constructors, inheritance, encapsulation, and polymorphism. Key operations and methods for file manipulation and object creation are detailed with examples.

Uploaded by

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

Python UNIT 4 New

This document covers file handling in Python, including types of files (text and binary), operations such as creating, opening, reading, writing, and closing files, as well as file paths and the format operator. It also introduces object-oriented programming concepts, including classes, objects, constructors, inheritance, encapsulation, and polymorphism. Key operations and methods for file manipulation and object creation are detailed with examples.

Uploaded by

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

UNIT 4

File Handling: File Types; Operations on Files– Create, Open, Read, Write, Close Files; File
Names and Paths; Format operator.
Object Oriented Programming: Classes and Objects; Creating Classes and Objects;
Constructor Method; Classes with Multiple Objects; Objects as Arguments; Objects as Return
Values; Inheritance- Single and Multiple Inheritance, Multilevel and Multipath Inheritance;
Encapsulation- Definition, Private Instance Variables; PolymorphismDefinition, Operator
Overloading.

File handling
Files
 A file is the common storage unit in a computer, and all programs and data are “written” into a file
and “read” from a file.it is used to permanently store data in a non-volatile memory(e.g hard disk).
 Since RAM is volatile which loses its data when computer is turned off, we use files for future use of
the data.

File types
Python supports two types of files.
1. Text Files
2. Binary Files
1. Text files :
 The text files contain data stored as a series of bits (binary values of 1s and 0s), the bits in text
files represent characters or strings.
 A text file is simply a sequence of ASCII or Unicode characters. In text file everything will be stored
as a character.
 In text file each line is terminated by special character called EOL.in text file some translation takes
place when this EOL character is read or written. In python EOL is ‘\n’ or ‘\r’ or combination of
both.
 Python programs, contents written in text editors are some of the example of text files.
 Common extensions for text file formats:
web standards: html, xml, css, svg, json,...
Source code: c, cpp, h, cs, js, py, java, rb, pl, php, sh,...
Documents: txt, tex, markdown, asciidoc, rtf, ps,...
Configuration: ini, cfg, rc, reg,...
Tabular data: csv, tsv,...
2. Binary files:
 The binary files contain data stored as a series of bits (binary values of 1s and 0s), bits in binary
files represent custom data.
 Binary files contain a sequence of bytes or ordered groupings of eight bits.
 While retrieving data from the binary file,the programmer can retrieve it in the form of bytes.
 A binary file stores the data in the same way as stored in the memory i.e data is stored according to
its data type so no translation occurs.
 Binary files are faster and easier for a program to read and write than text files.
 Binary file formats may include multiple types of data in the same file, such as image, video,
and audio data.
 We can’t read a binary file using a text editor
 Common extensions for binary file formats:
images: jpg, png, gif, bmp, tiff, psd,...
Videos: mp4, mkv, avi, mov, mpg, vob,...
Audio: mp3, aac, wav, flac, ogg, mka, wma,...
Documents: pdf, doc, xls, ppt, docx, odt,...
Archive: zip, rar, 7z, tar, iso,...
Database: mdb, accde, frm, sqlite,...
Executable: exe, dll, so, class,...

Operations on file
Create Files
 In Python, you use the open() function with one of the following options – "x" or "w" – to create a new file:
 "x" – Create: this command will create a new file if and only if there is no file already in existence with
that name or else it will return an error.
Example:
f = open("myfile.txt", "x")
It created a new empty text file .if you try to create a new file with the same name as you used above you will
get an error notifying you that the file already exists.

Opening files:
A file is opened using open() function, it returns a file object, also called a file handler that provides
methods for accessing the file.
Synatx: file_handler = open(filename, mode)
Ex: file_handler = open("example.txt")
file_handler = open("moon.txt","r")
file_handler = open("c:\file1.txt",""w)
 file_handler: file_handler object returned for filename
 file name :name of the file that we want to access.
 Mode: which describe purpose of the file to open.i e read ,write, append etc It is optional , if it
is not mention it will take default value as r.
Different File modes are
Read Only ('r’): This mode opens the text files for reading only. The start of the file is where the handle is
located. It raises the I/O error if the file does not exist. This is the default mode for opening files as well.
Ex:f1=open(“file1.txt”,”r”)

Write Only ('w’): This mode opens the file for writing only. The data in existing files are modified and
overwritten. The start of the file is where the handle is located. If the file does not already exist in the folder, a
new one gets created.
Ex:f1=open(“file2.txt”,”w”)

Append Only ('a’): This mode allows the file to be opened for writing. If the file doesn't yet exist, a new one
gets created. The handle is set at the end of the file. The newly written data will be added at the end, following
the previously written data.
Ex:f1=open(“file2.txt”,”a”)

Read and Write ('r+’): This method opens the file for both reading and writing. The start of the file is where
the handle is located. If the file does not exist, an I/O error gets raised.
Ex:f1=open(“file2.txt”,”r+”)

Write and Read ('w+’): This mode opens the file for both reading and writing. The text is overwritten and
deleted from an existing file. The start of the file is where the handle is located.
Ex:f1=open(“file2.txt”,”w+”)

Append and Read (‘a+’): Using this method, you can read and write in the file. If the file doesn't already exist,
one gets created. The handle is set at the end of the file. The newly written text will be added at the end,
following the previously written data.
Ex:f1=open(“file2.txt”,”a+”)

While using binary files, we have to use the same modes with the letter ‘b’ at the end. So that Python can
understand that we are interacting with binary files.
 ‘wb’ – Open a file for write only mode in the binary format.
 ‘rb’ – Open a file for the read-only mode in the binary format.
 ‘ab’ – Open a file for appending only mode in the binary format.
 ‘rb+’ – Open a file for read and write only mode in the binary format.
 ‘ab+’ – Open a file for appending and read-only mode in the binary format.
Read data from the text file:
When you use the open () function a file object is created. The list of methods that can be called on this
object. There are 3 methods of reading data from file.
1.Read() : this method is used to read the contents of a file up to a size and return it as a string. The size is
optional, and, if it is not specified, then the entire contents of the file will be read and returned.
Syntax: file_handler.read([size])
f1.txt
hi
hello
welcome
Ex:f = open("f1.txt", "r")
print(f.read(1)) output: h

2.The readline() method:


This function reads a line from a file and returns it as a string. It reads at most n bytes for the specified n. But
even if n is greater than the length of the line, it does not read more than one line.
f = open("f1.txt ", "r")
print(f.readline()) output: hi

3, Readlines():This function reads a line from a file and returns it as a string. It reads at most n bytes for the
specified n. But even if n is greater than the length of the line, it does not read more than one line.
Syntax: file_handler.readlines()
Ex: f = open("f1.txt", "r")
f.readlines() output :['hi\n', 'hello\n', 'welcome\n']
Write data to the text file:
There are two methods of writing to a file in Python, which are:
1. Write():this method will write the contents of the string to the file, returning the number of characters
written. If you want to start a new line, must include the new line character
Synatx: file_handler.write(string)
Ex: file_handler = open("moon.txt","w")
file_handler.write("moon is a natural satellite")

2.Writelines():this method will write a sequence of strings to the file.


Syntax: file_handler.writelines(sequence) output
Ex: file_handler = open("moon.txt","w") aaa
file_handler.writelines(["aaa\n","bbb\n","cccc\n"]) bbb
ccc
 tell(): this method returns an integer giving the file handler’s current position within the file, measured in
bytes from the beginning of the file.
Syntax: file_handler.tell()
Ex: file_handler = open("moon.txt","w")
file_handler.tell()

 Seek():this method is used to change the file handler’s position. The position is computed from adding
offset to a reference point.
Synatx: file_handler. Seek(offset, from_what)
The reference point is selected by the from_what argument.it accepts three values:
 0:sets the reference point at the beginning of the file.
 1: sets the reference point at the current file position.
 2: sets the reference point at the end of the file. If the from_what argument is omitted, then a default
value of 0 is used, indicating that the beginning of the file itself is the reference point.
Ex: f = open('workfile', 'w')
f.write('0123456789abcdef')
f.seek(2) // move the file pointer 2 characters ahead from the beginning of a file.
f.seek(2, 1) //// move the file pointer 2 characters ahead from the current position.
f.seek(-2, 1) //// move the file pointer 2 characters behind from the current position.

Closing text files:


 It is important to close the file once the processing is completed.
 After the file handler object is closed, file cannot further read or write from the file. Any attempt to
use the file handler object after being closed will result in an error.
 The close() function is usedto close the file.
Syntax: file_handler.close()
Ex:file_handler=open("moon.txt","r")
file_handler.close()

Filenames and paths


 Files are organized into directories (also called “folders”). Every running program has a “current
directory,” which is the default directory for most operations.
 For example, when you open a file for reading, Python looks for it in the current directory.
 The os module provides functions for working with files and directories (“os” stands for “operating
system”).
 os.getcwd returns the name of the current directory:
>>> import os
>>> cwd = os.getcwd()
>>> print cwd
/home/dinsdale
 cwd stands for “current working directory.” The result in this example is /home/dinsdale, which
is the home directory of a user named dinsdale.
 A string like cwd that identifies a file is called a path.
 A relative path starts from the current directory.
 An absolute path starts from the topmost directory in the file system.
 The paths we have seen so far are simple filenames, so they are relative to the current directory.
 To find the absolute path to a file, you can use os.path.abspath:
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
 os.path.exists checks whether a file or directory exists:
>>> os.path.exists('memo.txt')
True
 If it exists, os.path.isdir checks whether it’s a directory:
>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True
 Similarly, os.path.isfile checks whether it’s a file. os.listdir returns a list of the files (and other
directories) in the given directory:
>>> os.listdir(cwd)
['music', 'photos', 'memo.txt']
Format operator
 In file handling, the format operator is typically used to specify the formatting of data when reading
from or writing to a file.
 In Python, the format operator is represented by the % symbol. It allows you to format strings by
replacing placeholders with corresponding values.
 The format operator is often used in conjunction with the % formatting codes, which specify the type
and format of the values being inserted.

Ex: print('in %d years i have spotted %g %s.' % (3, 0.1, 'camels'))


The following example uses "%d" to format an integer, "%g" to format a floating-point number, and
"%s" to format a string:
Output:
In 3 years i have spotted 0.1 camels.

Ex: a = "anu" b="sonu"


Print(“%s and %s are good friend” %(a,b))
Output:
Anu and sonu are good friend

Object oriented programming


 In object-oriented programming, everything is just like a real-world object. In the real world,
everything is an object. An object can have state and behavior. An object in the real world can
communicate with another object.
 Python is an object-oriented programming language, everything is in Python treated as an object,
including variable, function, list, tuple, dictionary, set, etc.
 Every object belongs to its class. For example - An integer variable belongs to integer class.
 Almost everything in Python is an object, with its properties and methods.
 Class objects are often used to model the real-world objects that you find in everyday life.
 examples of real-world objects: your dog, your desk, your television set, your bicycle.
 Real-world objects share two characteristics: They all have state and behavior. Dogs have state (name,
color, breed, hungry) and behavior (barking, fetching, wagging tail)

Creating Classes
 In object-oriented programming (OOP), a class is a blueprint or template for creating objects
(instances).
 It defines the common attributes (data) and methods (functions) that define its behavior.
 Classes are defined by using the class keyword, followed by the ClassName and a colon.
Syntax: class ClassName:
<statement-1>
...
<statement-N>

Example : class MyClass:


def __init__(self, name):
self.name = name
def greet(self):
print("Hello, " + self.name + "!")
# Creating an object of the class
obj = MyClass("John")
# Accessing attributes and calling methods of the object
print(obj.name) # Output: John
obj.greet() # Output: Hello, John!
 In the above example, we define a class named MyClass. It has an __init__ method(constructor) that
initializes the name attribute of the class.
 The greet method is a simple method that prints a greeting message using the name attribute.
 To create an instance (object) of the class, we simply call the class name followed by parentheses,
passing any required arguments to the __init__ method. In this case, we create an object obj of MyClass
and pass the name "John" to initialize the name attribute.
 We can then access the attributes and call the methods of the object using the dot notation. In the
example, we print the value of the name attribute and call the greet method to display the greeting
message.
 By creating classes in Python, you can define your own custom types with specific attributes and
behaviors, encapsulating related data and functionality into a single unit.

Creating objects
Object refers to a particular instance of a class where the object contains variables and methods
defined in the class.
Synatx: object_name = ClassName(argument_1, argument_2, ….., argument_n)
Where arguments are optional
The syntax to access data attribute is,
Syntax :object_name.data_attribute_name
The syntax to assign value to data attribute is,
Syntax : object_name.date_attribute_name = value
Where value can be of integer, float, string types, or another object itself. The
syntax to call method attribute is,
Syntax : object_name.method_attribute_name()
Ex: class MyClass:
x=5
p1 = MyClass()
print(p1.x) Output: 5

Where MyClass is class name, x data attribute is defined inside the class, p1 is the object, throughp1.x
access the value of x.

The constructor method


 Python uses a special method called a constructor method. Python allows you to define only one
constructor per class.
 Also known as the __init__() method, it will be the first method definition of a class.
Syntax: def __init__(self, parameter_1, parameter_2, …., parameter_n):
statement(s)
 The __init__() method defines and initializes the instance variables. It is invoked as soon as an
object of a class is instantiated.
 The parameters for __init__() method are initialized with the arguments passed during creation
of the class object.
 Class methods that begin with a double underscore ( ) are called special methods as they have special
meaning.
 The number of arguments during the instantiation of the class object should be equivalent to the
number of parameters in init () method (excluding the self parameter).
Program to Illustrate constructor Method
class Mobile:
def __init__(self, name):
self.mobile_name = name
def receive_message(self):
print(f"Receive message using {self.mobile_name} Mobile")
def send_message(self):
print(f"Send message using {self.mobile_name} Mobile")
nokia = Mobile("Nokia")
nokia.receive_message()
nokia.send_message()
output
Receive message using Nokia Mobile
Send message using Nokia Mobile
Class with multiple object
Multiple objects for a class can be created while attaching a unique copy of data attributes and methods of the
class to each of these objects.
Program to Illustrate the Creation of Multiple Objects for a Class
class Birds:
def __init__(self, bird_name):
self.bird_name = bird_name
def flying_birds(self):
print(f"{self.bird_name} flies above clouds")
def non_flying_birds(self):
print(f"{self.bird_name} is the national bird of Australia")
pigeon = Birds("Pigeon ")
emu = Birds("Emu")
pigeon.flying_birds()
emu.non_flying_birds()
OUTPUT
Pigeon flies above clouds
Emu is the national bird of Australia
Here pigeon and emu are the two objects created for same class called Birds.

Objects as arguments
An object can be passed to a calling function as an argument.

Program to Demonstrate Passing of an Object as an Argument to a Function Call


class track:
def __init__(self, song, artist):
self.song = song
self.artist = artist
def print_track_info(info):
print(f"Song is '{info.song}'")
print(f"Artist is '{info.artist}'")
singer = Track("Roja", "Rehaman")
print_track_info (singer)

output
Song is Roja
Artist is Rehaman
In the class song, the __init__() method is added with the song and artist data attributes.The print_track_info()
method receives an object as parameter. The object singer of track class is passed as an argument to
print_track_info () method.

Objects as Return Values.


 The everything in Python is an object, including classes. Anything that can be used as a value (int, str,
float, functions,modules, etc.) is implemented as an object.
 The id() function is used to find the identity of the location of the object in memory
Syntax : id(object)
Ex: id(singer)
 This function returns the “identity” of an object.
 We can Check whether an object is an instance of a given class or not by using the isinstance() function.
Syntax: isinstance(object, classname)
 Where the object is an object instance and classname is a class, or a tuple containing classes, or other
tuples. The isinstance() function returns a Boolean true if the object is an instance or subclass of another
object otherwise false.

Inheritance
 Inheritance can be defined as a process through which one class acquires the features(attributes and
methods) of an existing class without modifying it.
 The class which inherits the features is referred to as child class or derived class and the class from
which the features inherited is referred to as parent class or base class.
 In other words, the newly formed class is the child class while the existing class is known as the parent
class.
 For instance, in the real world, a father and mother denote the parent class while their kids denote the
child class.
 A kid has acquired several features from their parents and at the same time, the kid has got some unique
features that the parents may not have.
 In programming terms, we can say that a child class acquires all the attributes and methods of a parent
class, but at the same time child class holds its own unique characteristics.
Syntax
Class Parent_class:
Body of parent_class
Class Child_class(Parent_class):
Body of Child_class

Ex: class Vehicle:


def Vehicle_info(self):
print('Inside Vehicle class')
class Car(Vehicle):
def car_info(self):
print('Inside Car class')
Car is the derived class and Vehicle is the base class.

Types of inheritance
Single Inheritance in Python
 Single inheritance is one of the simplest and easiest types of inheritance. In single inheritance, the child
class inherits all the attributes and methods in the parent class.
 This enables code reusability and modularity.
 In this case, class A is the parent class and class B is the child class. Class B has its own unique
attributes and method even then it inherits the attributes and methods of class A.

Syntax
class ParentClass:
# Parent class attributes and methods
class ChildClass(ParentClass):
# Child class attributes and methods
Example
class Vehicle: #Base Class
def Vehicleinfo(self):
print('Inside Vehicle class')
class Car(Vehicle): #Derived Class
def carinfo(self):
print('Inside Car class')
c = Car() # Create object of Car
c.Vehicleinfo()
c.carinfo()

output:
Inside Vehicle class
Inside Car class
Multiple Inheritance
 Multiple inheritance is a concept in object-oriented programming (OOP) where a derived class inherits
properties and behavior from multiple base classes.
 In this type of inheritance, a class can inherit attributes and methods from more than one parent class,
combining their functionality into a single derived class.
Syntax
class ParentClass1:
# Parent Class 1 attributes and methods
class ParentClass2:
# Parent Class 2 attributes and methods
class ChildClass(ParentClass1, ParentClass2):
# Child Class attributes and methods

Program to Demonstrate Multiple Inheritance


class Person: # Base class 1
def person_info(self, name, age):
print('Inside Person class')
print('Name:', name, 'Age:', age)

class Company: # Base class 2


def company_info(self, cname, loc):
print('Inside Company class')
print('Name:', cname, 'location:', loc)

class Employee(Person, Company): # Derived class def


Employee_info(self, salary, skill):
print('Inside Employee class')
print('Salary:',salary, 'Skill:', skill)
emp = Employee() # Create object of Employee
emp.person_info('Jesica', 28) # access data
emp.company_info('Google', 'USA')
emp.Employee_info(120000, 'Machine Learning')
Output
Name: Jesica, Age: 28
Name: Google, location:USA
Salary:120000, Skill: Machine Learning

Multilevel Inheritance
 Multilevel inheritance is a type of inheritance where a class is created from a derived class which itself
inherits a base class.
 A multilevel inheritance shows the possibility of inheriting from a derived class or child class.
 So a minimal multilevel inheritance is 3 tier structure with a child class that inherits features from a derived
class which in turn inherits the properties from a superclass

Syntax
class Grandparent:
# Grandparent class attributes and methods
class Parent(Grandparent):
# Parent class attributes and methods
class Child(Parent):
# Child class attributes and methods
 In this example, the DerivedClass inherits from the IntermediateClass, which in turn inherits from the
BaseClass, creating a multilevel inheritance chain.
 The DerivedClass can access and extend the attributes and methods defined in both parent classes.

Program to illustrate multilevel inheritance


class Vehicle: #Main Base class
def Vehicle_info(self):
print('Inside Vehicle class')
class Car(Vehicle): #Derived class of Vehicle or intermediate class
def car_info(self):
print('Inside Car class')
class SportsCar(Car): #Derived class
def sports_car_info(self):
print('Inside SportsCar class')
s_car = SportsCar() # Create object of Sports Car
s_car.Vehicle_info() # access Vehicle's and Car info using SportsCar object
s_car.car_info()
s_car.sports_car_info()
output
Inside Vehicle classInside Car
class Inside SportsCar

Multipath Inheritance
 A class is derived from two or more classes which are derived from the base class such type of
inheritance is called multipath inheritance

Class D

Syntax: class Baseclass: #Main Base class


# Base class attributes and methods
class DerivedClassName1(Baseclass) # Derived class1 of Base class
# Derived class 1 attributes and methods
class DerivedClassName2(Baseclass): #Derived class 2 of Base class
# Derived class 2 attributes and methods
class DerivedClassName3(DerivedClassName1, DerivedClassName2):
# Derived class 3 attributes and methods
Program to illustrate multipath inheritance
class Vehicle:
def vehicle_info(self):
print("Inside Vehicle class")

class Car(Vehicle):
def car_info(self):
print("Inside Car class")

class Truck(Vehicle):
def truck_info(self):
print("Inside Truck class")
class SportsCar(Car, Vehicle): # Sports Car can inherits properties of Vehicle and Car
def sports_car_info(self):
print("Inside SportsCar class")
s_car = SportsCar() # create object of SportCar class
s_car.vehicle_info()
31s_car.car_info()
s_car.truck_info()
s_car.sports_car_info()
output
Inside Vehicle class
Inside Car class
Inside Truck class
Inside Sports Car

Encapsulation
Encapsulation is an object-oriented programming concept that involves hiding the internal stateand
implementation details of an object and providing controlled access to it through methods.
Definition:
 Encapsulation is the process of combining variables that store data and methods that work on those
variables into a single unit called class.
 In Encapsulation, the variables are not accessed directly; it is accessed through the methods present
in the class. Encapsulation ensures that the object’s internal representation are hidden from the rest of
the application.
 In Python, you can achieve encapsulation by using private instance variables.

Private instance variables and methods


 Instance variables or methods, which can be accessed within the same class and cannot be access
outside the class are called private instance variables or private methods.
 They are typically denoted by prefixing an double underscore (__) to their names.
 Although Python does not enforce strict data hiding or access restrictions, the use of the underscore
convention indicates that the variable should be treated as private and should not be accessed directly
from outside the class.
Program to demonstrate private instance variable to achieve encapsulation
class Person:
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def set_age(self, age):
if age > 0:
self.__age = age
person = Person("John", 25) # Creating an object of the Person class
print(person.get_name()) # Accessing private instance variables using public methods
print(person.get_age())
print(person.__name) # Attempting to access private instance variables directly
print(person.__age)
output
John
25
print(person.__name)
AttributeError: 'Person' object has no attribute '__name'

In the above example, the Person class has private instance variables __name and __age.These
variables are accessed through public methods get_name() and get_age().private instance variables
cannot be accessed directly outside the class.

Polymorphism
 Polymorphism is having different forms. Polymorphism refers to a function having the same name
but being used in different ways and different scenarios.
 It basically creates a structure that can use many forms of objects. This polymorphism may be
accomplished in two distinct ways: overloading and overriding.
Example: add(x, y, z = 0):
return x + y + z
print(add(2, 3))
print(add(2, 3, 4))

Operator overloading
 Operator overloading is a kind of overloading in which an operator may be used in ways other than
those stated in its predefined definition.
>>>print(2*7)
14
>>>print("a"*3)
aaa
 Thus, in the first example, the multiplication operator multiplied two numbers; but, in the second, since
multiplication of a string and an integer is not feasible, the character is displayed three times twice.
Ex: class example:
def__init__(self, X):
self.X = X
def__add__(self, U):
return self.X + U.X
object_1 = example( int( input( print ("Please enter the value: "))))
object_2 = example( int( input( print ("Please enter the value: "))))
print (": ", object_1 + object_2)
object_3 = example(str( input( print ("Please enter the value: "))))
object_4 = example(str( input( print ("Please enter the value: "))))
print (": ", object_3 + object_4)

You might also like