UNIT 4 Python
UNIT 4 Python
What is File?
A file is a container in a computer system that stores data, information,
settings, or commands, which are used with a computer program.
1. Text File
• Text file store the data in the form of characters.
• Text file are used to store characters or strings.
• Usually, we can use text files to store character data
• e.g.: xyz.txt
Example:
• Web standards: html, XML, CSS, JSON etc.
• Source code: c, app, js, py, java etc.
• Documents: txt, tex, RTF etc.
• Tabular data: csv, tsv etc.
• Configuration: ini, cfg, reg etc.
•
2. Binary File
• Binary file store entire data in the form of bytes.
• Binary file can be used to store text, image, audio and video.
• Usually we can use binary files to store binary data like
images,video files, audio files etc
Example:
• Document files: .pdf, .doc, .xls etc.
• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.
Opening a file
Python provides an open() function that accepts two arguments, file name
and access mode in which the file is accessed. The function returns a file
object which can be used to perform various operations like reading,
writing, etc.
Syntax:
Example1:
f1=open("myfile.txt",'r')
#file object
print(f1.read())
If the file is located in a different location, you will have to specify the file
path, like this:
Example2:
Open a file on a different location:
f = open("C:\\myfiles\myfile.txt", "r")
print(f.read())
In the above program, file called myfile is opened and we can read the file
using inbuilt function called read().
The files can be accessed using various modes like read, write, or append.
The following are the details about the access mode to open a file.
SN Access Description
mode
3 r+ It opens the file to read and write both. The file pointer
exists at the beginning of the file.
4 rb+ It opens the file to read and write both in binary format.
The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format.
The file pointer exists at the beginning of the file.
By calling readline() two times, you can read the two first lines:
f = open("myfile.txt", "r")
print(f.readline())
print(f.readline())
output:
Hello welcome to myfile.txt
This file is a text file created in note pad
Close Files
It is a good practice to always close the file when you are done with it.
There is a built_in method called close(),which is used to close the file
once work is done.
Syntax:
Fileobject.close()
Example
Close the file when you are finish with it:
f = open("myfile.txt", "r")
print(f.readline())
f.close()
Example :
Open the file "myfile.txt" and append content to the file:
f = open("myfile2.txt", "a")
f.write(" Now the file has more content!")
f.close()
Example2
Open the file "myfile.txt" and overwrite the content:
f = open("myfile.txt", "w")
f.write("oops! I have deleted the content!")
f.close()
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example1
Create a file called "myfile.txt":
f = open("newfile.txt", "x")
Result: a new empty file is created!
Example2
Create a new file if it does not exist:
f = open("newfile.txt", "w")
Python Delete File
Delete a File
Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")
o Class
o Object
o Method
o Inheritance
o Polymorphism
o Data Abstraction
o Encapsulation
Class
The class can be defined as a collection of objects. It is a logical entity that
has some specific attributes and methods. For example: if you have an
employee class, then it should contain an attribute and method, i.e. an
email id, name, age, salary, etc.
Syntax
class ClassName:
<statement-1>
.
<statement-N>
Example:
class myclass:
str = 'hello im data member of class'
a = 10
def mymethod(self):
print("hello im member function of the class")
obj = myclass()
print(obj.str)
print(obj.a)
obj.mymethod()
output:
hello im data member of class
10
hello im member function of the class
Object
The object is an entity that has state and behaviour. It may be any real-
world object like the mouse, keyboard, chair, table, pen, etc.
obj=sample()
print(obj.x)
output:
10
In the above program we have created the one object called obj.
Using that object we have accessing the x value
obj1=sample()
obj2=sample()
print(obj1.x)
print(obj2.x)
output:
10
10
Python Consructor
Constructors are special methods generally used for instantiating an
object. The task of constructors is to initialize (assign values) to the data
members of the class when an object of the class is created. In Python
the __init__() method is called the constructor and is always called when
an object is created.
def __init__(self):
# body of the constructor
Types of constructors :
Default constructor: The default constructor is a simple
constructor which doesn’t accept any arguments. Its definition has
only one argument which is a reference to the instance being
constructed.
Example:
class sample:
def __init__(self):
self.name="Im default constructor"
def mymethod(self):
print(self.name)
obj1=sample()
obj1.mymethod()
output: Im default constructor
obj1=sample(10,20)
output: 30
Example2:
class sample:
def __init__(self,a,b):
self.a = a
self.b = b
def mymethod(self):
print(self.a + self.b)
obj1=sample(10,20)
obj1.mymethod()
output: 30
Python Inheritance
A class that inherits all the methods and properties from another class is
known as inheritance
Parent class is the class being inherited from, also called base class.
Child class is the class that inherits from another class, also called
derived class.
Class parent_class:
# body
Child_class(parentclass):
# body
1. Single inheritance
2. Multiple inheritance
3. Multilevel inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
class parent:
def method1(self):
print("im parent class method")
class child(parent):
def method2(self):
print("im child class method")
obj=child()
obj.method1()
obj.method2()
output:
im parent class method
im child class method
Example2:
class parent:
def method1(self,a,b):
print("addition of two numbers is:",a+b)
class child(parent):
def method2(self,a,b):
print("subtraction of two numbers is:",a-b)
obj=child()
obj.method1(100,50)
obj.method2(100,50)
output:
addition of two numbers is: 150
subtraction of two numbers is: 50
Syntax:
class class1:
<class-suite>
class class2(class1):
<class suite>
class class3(class2):
<class suite>
Example1:
class parent:
def method1(self):
print("I am parent class method")
class child_parent(parent):
def method2(self):
print("I am child class method and also parent for another class")
class child2(child_parent):
def method3(self):
print("I am child class method")
obj=child2()
obj.method1()
obj.method2()
obj.method3()
output:
I am parent class method
I am child class method and also parent for another class
I am child class method
Example2:
class parent:
def method1(self,a,b):
print("addition of two numbers is:",a+b)
class child_parent(parent):
def method2(self,a,b):
print("subtraction of two numbers is:",a-b)
class child2(child_parent):
def method3(self,a,b):
print("multiplication of two numbers is:",a*b)
obj=child2()
obj.method1(100,200)
obj.method2(120,60)
obj.method3(40,4)
output:
addition of two numbers is: 300
subtraction of two numbers is: 60
multiplication of two numbers is: 160
3.Python Multiple inheritance
One child or derived class will inherit the properties and methods of more
than one parent class is known as multiple inheritance.
Syntax
class Base1:
<class-suite>
class Base2:
<class-suite>
.
class BaseN:
<class-suite>
Example1:
class parent1:
def method1(self):
print("I am parent class method")
class parent2:
def method2(self):
print("I am child class method and also parent for another class")
class child(parent1,parent2):
def method3(self):
print("I am child class method")
obj=child()
obj.method1()
obj.method2()
obj.method3()
output:
I am parent class method
I am child class method and also parent for another class
I am child class method
Example2:
class parent1:
def method1(self,a,b):
print("addition of two numbers is:",a+b)
class parent2:
def method2(self,a,b):
print("subtraction of two numbers is:",a-b)
class child(parent1,parent2):
def method3(self,a,b):
print("multiplication of two numbers is:",a*b)
obj=child()
obj.method1(100,200)
obj.method2(120,60)
obj.method3(40,4)
output:
addition of two numbers is: 300
subtraction of two numbers is: 60
multiplication of two numbers is: 160
4.Hierarchical inheritance
More than one child class will inherit the properties and methods of one
parent class
Parent class
Child1 Child2
Example1:
class parent:
def method1(self):
print("I am parent class method")
class child1(parent):
def method2(self):
print("I am child class method")
class child2(parent):
def method3(self):
print("I am also child class method")
obj1=child1()
obj2=child2()
obj1.method1()
obj1.method2()
obj2.method1()
obj2.method3()
output:
I am parent class method
I am child class method
I am parent class method
I am also child class method
Example2:
class parent:
def method1(self,a,b):
print("addition of two numbers is:",a+b)
class child1(parent):
def method2(self,a,b):
print("subtraction of two numbers is:",a-b)
class child2(parent):
def method3(self,a,b):
print("multiplication of two numbers is:",a*b)
obj1=child1()
obj2=child2()
obj1.method1(100,200)
obj1.method2(200,100)
obj2.method1(20,4)
obj2.method3(20,5)
Output:
addition of two numbers is: 300
subtraction of two numbers is: 100
addition of two numbers is: 24
multiplication of two numbers is: 100
5.Hybrid inheritance
Hybrid inheritance is a combination of more than one type of
inheritance.
Parent class
Child_parent Child2
Child1
Example:
class parent:
def method1(self):
class child_parent(parent):
def method2(self):
print("I am child class method and also parent for another class")
class child1(child_parent):
def method3(self):
class child2(parent):
def method4(self):
obj1=child1()
obj1.method1()
obj1.method2()
obj1.method3()
obj2=child2()
obj2.method1()
obj2.method4()
output:
Method Overriding:
Two or more methods can be defined with same name and same
parameters is known as method overriding.
class child1(parent):
def method1(self):
print("I am child class method")
obj1=child1()
obj1.method1()
Output:
I am child class method
Encapsulation in Python
Encapsulation is one of the most fundamental concepts in object-oriented
programming (OOP). This is the concept of wrapping data and methods
that work with data in one unit. This prevents data modification accidentally
by limiting access to variables and methods. An object's method can change
a variable's value to prevent accidental changes. These variables are called
private variables.
Private Members
Private members are the same as protected members. The difference is
that class members who have been declared private should not be accessed
by anyone outside the class or any base classes. Python does not have
Private instance variables that can be accessed outside of a class.
Example:
In the below example we are created two private variables that is a and b
and accessing those variables inside the class
class myclass:
__a=10
__b='Lavanya'
print(__a)
print(__b)
Output:
10
Lavanya
In the other example we are trying to access the private members outside
the class means it’s thrown an error.
class myclass:
__a=10
__b='Lavanya'
obj=myclass()
print(obj.__a)
print(obj.__b)
Output:
print(obj.__a)
^^^^^^^
AttributeError: 'myclass' object has no attribute '__a'
Protected Members
Protected members can be accessed within the class, outside
The class and also in the derived class.
Protected members can be defined prefix the members with single
underscore.
Example:
class myclass:
_a=10
_b='Lavanya'
obj=myclass()
print(obj._a)
print(obj._b)
Output:
10
Lavanya
Public members
Public members can be accessed anywhere in the class outside the class
and also in other classes.
Polymorphism in Python:
The word polymorphism means having many forms. In other words
Same function name can be used for different purpose.
Examples for polymorphism is
Method overloading
Method overriding
operator overloading
python doesn’t support for the method overloading
Method overriding:
Method overriding is implanted using inheritance
Two or more methods can be defined with same name and same
parameters is known as method overriding.
Example:
class parent:
def method1(self):
print("I am parent class method")
class child1(parent):
def method1(self):
print("I am child class method")
obj1=child1()
obj1.method1()
Output:
I am child class method
Operator overloading:
Same operator is used for different purpose, means + operator is used
for adding two numbers and also adding two strings, same operator is
used differently with objects of the same class this process is known as
operator overloading.
Suppose the user has two objects which are the physical representation of
a user-defined data type class. The user has to add two objects using the
"+" operator, and it gives an error. This is because the compiler does not
know how to add two objects. So, the user has to define the function for
using the operator, and that process is known as "operator overloading".
The user can overload all the existing operators by they cannot create any
new operator. Python provides some special functions, or we can say magic
functions for performing operator overloading, which is automatically
invoked when it is associated with that operator. Such as, when the user
uses the "+" operator, the magic function __add__ will automatically
invoke in the command where the "+" operator will be defined.
Example:
class method_overloading:
def __init__(self,a):
self.a=a
def __add__(self,b):
return self.a+b.a
obj1=method_overloading(int(input("enter a value=")))
obj2=method_overloading(int(input("enter b value=")))
print("addition of two objects is=",obj1+obj2)
Output:
enter a value=23
enter b value=45
addition of two objects is= 68
Binary Operators:
+ __add__(self, other)
- __sub__(self, other)
* __mul__(self, other)
/ __truediv__(self, other)
// __floordiv__(self, other)
% __mod__(self, other)
** __pow__(self, other)
| __or__(self, other)
^ __xor__(self, other)
Comparison Operators:
== __EQ__(SELF, OTHER)
!= __NE__(SELF, OTHER)
Assignment Operators:
-= __ISUB__(SELF, OTHER)
+= __IADD__(SELF, OTHER)
*= __IMUL__(SELF, OTHER)
/= __IDIV__(SELF, OTHER)
%= __IMOD__(SELF, OTHER)
|= __IOR__(SELF, OTHER)
^= __IXOR__(SELF, OTHER)
Unary Operator:
- __NEG__(SELF, OTHER)
+ __POS__(SELF, OTHER)
Raw string in python
Python raw string is the special type of string that allows you to include
backslashes and that will treat as literal or character in the string.
In python raw strings are defined by prefixing a string literal with the
letter ‘r’.
Example1:
str=r"C:\Users\lavan\OneDrive\Desktop\python notes"
print(str)
output:
C:\Users\lavan\OneDrive\Desktop\python notes
Example2:
In the below given example string is not prefixed with r we are
trying to displaying the string that contains backslashes its throw
a error.
str=r"C:\Users\lavan\OneDrive\Desktop\python notes"
print(str)