Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

UNIT 4 Python

Notes

Uploaded by

bipruu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

UNIT 4 Python

Notes

Uploaded by

bipruu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

UNIT-4

File Handling In Python


File handling in Python is a powerful tool that can be used to
perform a wide range of operations on files.

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.

Types of Files in Python


1. Text File
2. Binary File

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.

Python File Handling Operations

Most importantly there are 4 types of operations that can be


handled by Python on files:
• Open
• Read
• Write
• Close
Other operations include:
• Rename
• Delete

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:

File_object = open(file-name, access-mode)

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

1 R It opens the file to read-only mode. The file pointer


exists at the beginning. The file is by default open in
this mode if no access mode is passed.

2 Rb It opens the file to read-only in binary format. The file


pointer exists at the beginning of the file.

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.

5 W It opens the file to write only. It overwrites the file if


previously exists or creates a new one if no file exists
with the same name. The file pointer exists at the
beginning of the file.

6 Wb It opens the file to write only in binary format. It


overwrites the file if it exists previously or creates a new
one if no file exists. The file pointer exists at the
beginning of the file.

7 w+ It opens the file to write and read both. It is different


from r+ in the sense that it overwrites the previous file
if one exists whereas r+ doesn't overwrite the
previously written file. It creates a new file if no file
exists. 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.

9 A It opens the file in the append mode. The file pointer


exists at the end of the previously written file if exists
any. It creates a new file if no file exists with the same
name.
10 Ab It opens the file in the append mode in binary format.
The pointer exists at the end of the previously written
file. It creates a new file in binary format if no file exists
with the same name.

11 a+ It opens a file to append and read both. The file pointer


remains at the end of the file if a file exists. It creates
a new file if no file exists with the same name.

12 ab+ It opens a file to append and read both in binary format.


The file pointer remains at the end of the file.

Read the content of the file:


By default the read() method returns the whole text for reading.
Syntax:
Fileobject.read()
Example:
F1=open(“myfile.txt”.”r”)
Print(F1.read())

Read Lines of the file


You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("myfile.txt", "r")
print(f.readline())
output:
Hello welcome to myfile.txt

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()

Python File Write


Write to an Existing File

To write to an existing file, you must add a parameter to


the open() function:

"a" - Append - will append to the end of the file

"w" - Write - will overwrite any existing content

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()

#open and read the file after the appending:


f = open("myfile.txt", "r")
print(f.read())
output:
Hello welcome to myfile.txt
This file is a text file created in note pad Now the file has more content!

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()

#open and read the file after the overwriting:


f = open("myfile.txt", "r")
print(f.read())
output:
oops! I have deleted the content!

Create a New File


To create a new file in Python, use the open() method, with one of the
following parameters:

"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

To delete a file, you must import the OS module, and run


its os.remove() function:

Example
Remove the file "demofile.txt":
import os
os.remove("demofile.txt")

Object oriented concepts in Python


Python Classes/Objects:
Python is an object oriented programming language.
Almost everything in Python is an object, with its properties and methods.

Major principles of object-oriented programming system are given below.

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.

We can use the class name to create the objects


class sample:
x=10

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

Creating multiple the objects


We can create the multiple objects for a class. In the below program we
have created the two objects called obj1 and obj2.
class sample:
x=10

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.

Syntax of constructor declaration :

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

parameterized constructor: constructor with parameters is


known as parameterized constructor. The parameterized
constructor takes its first argument as a reference to the instance
being constructed known as self and the rest of the arguments are
provided by the programmer.
class sample:
Example1:
def __init__(self,a,b):
self.a = a
self.b = b
print(self.a + self.b)

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

Advantages of using constructors in Python:

• Initialization of objects: Constructors are used to initialize


the objects of a class. They allow you to set default values for
attributes or properties, and also allow you to initialize the
object with custom data.
• Easy to implement: Constructors are easy to implement in
Python, and can be defined using the __init__() method.
• Better readability: Constructors improve the readability of the
code by making it clear what values are being initialized and
how they are being initialized.
• Encapsulation: Constructors can be used to enforce
encapsulation, by ensuring that the object’s attributes are
initialized correctly and in a controlled manner.

Disadvantages of using constructors in Python:


• Overloading not supported: Unlike other object-oriented
languages, Python does not support method overloading. This
means that you cannot have multiple constructors with different
parameters in a single class.
• Limited functionality: Constructors in Python are limited in
their functionality compared to constructors in other
programming languages. For example, Python does not have
constructors with access modifiers like public, private or
protected.
• Constructors may be unnecessary: In some cases,
constructors may not be necessary, as the default values of
attributes may be sufficient. In these cases, using a constructor
may add unnecessary complexity to the code.

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.

Benefits of inheritance are:


Inheritance allows you to inherit the properties of a class, i.e., base class
to another, i.e., derived class. The benefits of Inheritance in Python are
as follows:
• It represents real-world relationships well.
• It provides the reusability of a code. We don’t have to write
the same code again and again. Also, it allows us to add more
features to a class without modifying it.
• It is transitive in nature, which means that if class B inherits
from another class A, then all the subclasses of B would
automatically inherit from class A.
• Inheritance offers a simple, understandable model structure.
• Less development and maintenance expenses result from an
inheritance.

• in python, a derived class can inherit base class by just mentioning


the base in the bracket after the derived class name. Consider the
following syntax to inherit a base class into the derived class.

Syntax to reate inheritance:

Class parent_class:

# body

Child_class(parentclass):

# body

Types of inheritance in python:

Inheritance is classified into 5 types namely:

1. Single inheritance

2. Multiple inheritance

3. Multilevel inheritance

4. Hierarchical inheritance

5. Hybrid inheritance

1.Single inheritance: one child class will inherit the properties


and methods of one parent class is known as single inheritance
Example1:

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

2.Python Multi-Level inheritance


Multi-Level inheritance is possible in python like other object-oriented
languages. Multi-level inheritance is implemented when a derived class
inherits another derived class. There is no limit on the number of levels up
to which, the multi-level inheritance is archived in python.

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.

The syntax to perform multiple inheritance is given below.

Syntax
class Base1:
<class-suite>

class Base2:
<class-suite>
.
class BaseN:
<class-suite>

class Derived(Base1, Base2, ...... 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

Is known as hierarchical inheritance

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.

In this below example we are combining the multilevel and hierarchical


inheritance to form a hybrid inheritance.

Parent class

Child_parent Child2

Child1

Example:

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 child1(child_parent):
def method3(self):

print("I am child class method")

class child2(parent):

def method4(self):

print("I am child class method")

obj1=child1()

obj1.method1()

obj1.method2()

obj1.method3()

obj2=child2()

obj2.method1()

obj2.method4()

output:

I am parent class method

I am child class method and also parent for another class

I am child class method

I am parent class method

I am child class method

Method Overriding:
Two or more methods can be defined with same name and same
parameters is known as method overriding.

Using inheritance, we can implement method overriding. Same method is


defined in both parent and child class, then child class method will override
the parent class method this process is called 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

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.

Data (data Methods (member


members) functions)
Class
Encapsulation is demonstrated by a class which encapsulates all data, such as
member functions, variables, and so forth. It’s shown in the above figure.

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.

However, to define a private member, prefix the member's name with a


double underscore "__".

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.

Using inheritance, we can implement method overriding. Same method is


defined in both parent and child class, then child class method will override
the parent class method this process is called 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.

How to Overload the Operators in Python?

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

Python magic functions used for operator


overloading:

Binary Operators:

Operator Magic Function

+ __add__(self, other)

- __sub__(self, other)

* __mul__(self, other)

/ __truediv__(self, other)

// __floordiv__(self, other)

% __mod__(self, other)

** __pow__(self, other)

>> __rshift__(self, other)

<< __lshift__(self, other)

& __and__(self, other)

| __or__(self, other)

^ __xor__(self, other)

Comparison Operators:

Operator Magic Function

< __LT__(SELF, OTHER)

> __GT__(SELF, OTHER)


<= __LE__(SELF, OTHER)

>= __GE__(SELF, OTHER)

== __EQ__(SELF, OTHER)

!= __NE__(SELF, OTHER)

Assignment Operators:

Operator Magic Function

-= __ISUB__(SELF, OTHER)

+= __IADD__(SELF, OTHER)

*= __IMUL__(SELF, OTHER)

/= __IDIV__(SELF, OTHER)

//= __IFLOORDIV__(SELF, OTHER)

%= __IMOD__(SELF, OTHER)

**= __IPOW__(SELF, OTHER)

>>= __IRSHIFT__(SELF, OTHER)

<<= __ILSHIFT__(SELF, OTHER)

&= __IAND__(SELF, OTHER)

|= __IOR__(SELF, OTHER)

^= __IXOR__(SELF, OTHER)

Unary Operator:

Operator Magic Function

- __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)

You might also like