Python UNIT 4 New
Python UNIT 4 New
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
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")
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.
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>
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.
Objects as arguments
An object can be passed to a calling function as an argument.
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.
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
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
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.
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
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.
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)