0% found this document useful (0 votes)
2 views8 pages

Python Unit 4

This document covers file handling in Python, including reading and writing files, file types, and access modes. It also discusses object-oriented programming concepts such as classes, objects, constructors, and inheritance. Additionally, it provides examples and syntax for various operations related to file handling and object manipulation.

Uploaded by

Kanchan Patil
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)
2 views8 pages

Python Unit 4

This document covers file handling in Python, including reading and writing files, file types, and access modes. It also discusses object-oriented programming concepts such as classes, objects, constructors, and inheritance. Additionally, it provides examples and syntax for various operations related to file handling and object manipulation.

Uploaded by

Kanchan Patil
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/ 8

PYTHON PROGRAMMING UNIT IV

File Handling Read a file


 Every computer system uses files to save things To read a file using the Python script, the Python
from one computation to the next. provides the read() method. The read() method reads a
string from the file. It can read the data in the text as
Python provides many facilities for creating and
well as a binary format.
accessing files.
 File Types We can also open file for reading using argument ‘r’ and
There are mainly two types of data files prints its contents. Python treats file as a sequence of
1. Text file lines, we use for statement to iterate over file’s contents.
2. Binary File
Example:
A text file consists of human readable fileptr = open("file2.txt","r")
characters, which can be opened by any text editor.
content = fileptr.read(10)
Binary files are made up of non-human readable
print(type(content))
characters and symbols, which require specific programs
to access its contents. print(content)
fileptr.close()
 Operations on Files– Create, Open, Read,
Write, Close Files. Write in file

A file operation can be done in the following order. To write some text to a file, we need to open the file
using the open method with one of the following access
o Open a file modes.
o Read or write - Performing operation
w: It will overwrite the file if any file exists. The file
o Close the file pointer is at the beginning of the file.

Creating files a: It will append the existing file. The file pointer is at
filehandle = open(‘kids’ , ‘w’) instructs the the end of the file. It creates a new file if no file exists.
operating system to create a file with name kids & return
its filehandle for the file. The argument w indicates that Example
file is opened for writing. fileptr = open("file2.txt", "w")
Syntax: fileptr.write(Python has an easy syntax and user
fileobject = open(<file-name>, <access friendly interaction)
mode>, <buffering>) fileptr.close()
Opening a file Close Files
Python provides an open() function that accepts two Once all the operations are done on the file, we
arguments, file name and access mode in which the must close it through our Python script using
file is accessed. The function returns a file object the close() method. Any unwritten information gets
which can be used to perform various operations like destroyed once the close() method is called on a file
reading, writing, etc. object.
Example
fileptr = open("file.txt","r") Syntax

if fileptr: fileobject.close()
print("file is opened successfully")

1 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

 File Access Modes creates a new file if no file exists with the
same name.
Access Description
mode
ab It opens the file in the append mode in
binary format. The pointer exists at the
r It opens the file to read-only mode. The
end of the previously written file. It
file pointer exists at the beginning. The
creates a new file in binary format if no
file is by default open in this mode if no
file exists with the same name.
access mode is passed.
a+ It opens a file to append and read both.
rb It opens the file to read-only in binary
The file pointer remains at the end of
format. The file pointer exists at the
the file if a file exists. It creates a new file
beginning of the file.
if no file exists with the same name.
r+ It opens the file to read and write both.
ab+ It opens a file to append and read both
The file pointer exists at the beginning
in binary format. The file pointer remains
of the file.
at the end of the file.
rb+ It opens the file to read and write both
in binary format. The file pointer exists
at the beginning of the file. Common functions for accessing files are

w It opens the file to write only. It  open(fn, 'w') fn is a string representing a file name.
overwrites the file if previously exists or Creates a file for writing and returns a file handle.
creates a new one if no file exists with  open(fn, 'r') fn is a string representing a file name.
the same name. The file pointer exists at Opens an existing file for reading and returns a file
the beginning of the file.
handle.
wb It opens the file to write only in binary  open(fn, 'a') fn is a string representing a file name.
format. It overwrites the file if it exists Opens an existing file for appending and returns a
previously or creates a new one if no file file handle.
exists. The file pointer exists at the  fh.read() returns a string containing the contents of
beginning of the file. the file associated with file handle fh.
 fh.readline() returns the next line in the file
w+ It opens the file to write and read both.
It is different from r+ in the sense that it associated with the file handle fh.
overwrites the previous file if one exists  fh.readlines() returns a list each element of which is
whereas r+ doesn't overwrite the one line of the file associated with the file handle
previously written file. It creates a new fh.
file if no file exists. The file pointer exists  fh.write(s) write the string s to the end of the file
at the beginning of the file. associated with the file handle fh.
 fh.writeLines(S) S is a sequence of strings. Writes
wb+ It opens the file to write and read both
each element of S to the file associated with the file
in binary format. The file pointer exists
at the beginning of the file. handle fh.
 fh.close() closes the file associated with the file
a It opens the file in the append mode. handle fh
The file pointer exists at the end of the
previously written file if exists any. It

2 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

 File Names and Paths 3. Using the Pathlib module in python


Filename and path are two terminologies that are  Besides the OS library, python also provides a
associated with file handling. library that is dedicated to handling different
types of paths provided by different operating
 As the name suggests, the filename refers to the systems.
name of the actual file.  Inside the pathlib library, we can use the Path
 The path refers to the exact location of a file. function to get the filename from a given path.
 The Path function has two attributes: stem and
Methods to get filename from path in Python name.
 The stem attribute gives the filename without the
There are three methods that we can use to get the
extension
filename from a given path in python. Some of these  the name attribute gives the complete filename
methods use built-in functions, others use a module. along with the extension.
1. Split function in python  Example:
 Any path that is passed to the interpreter will be from pathlib import Path
a string value. file_path = "C:/Users/User1/Documents/file1.txt"
 When a path is passed as an input, it will look full_name = Path(file_path).name
like C:\Users\User1\Documents\file1.txt file_name = Path(file_path).stem
 We can use the built-in split function in python print(full_name)
to split the path name. We will split the path print(file_name)
name at every \.
 Once we do that, we will have a tuple that Output:
contains all the words between the slashes. file1.txt
 Then we print the last element of the tuple and file1
we get the filename with the extension.
 Example:
file_path = "C:/Users/User1/Documents/file1.txt"
file_name = file_path.split("/")[-1]
print(file_name)

OUTPUT:
file1.txt

2. OS module in python
 The OS module in python provides special
functions and methods for operating system
functionality like filename extraction.
 We can use the os.path.basename function to
get the filename from the path given by the user.
 we can use the os.path.splitext function to get
the filename without the extension.
 Example:
import os
file_path = "C:/Users/User1/Documents/file1.txt"
full_name = os.path.basename(file_path)
file_name = os.path.splitext(full_name)
print(full_name)
print(file_name[0])

Output:

file1.txt
file1

3 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

Object Oriented Programming


 Classes and Objects  Constructor Method
Class A constructor is a special type of method (function)
It is a logical entity that has some specific attributes which is used to initialize the instance members of
and methods. The class can be defined as a the class.
collection of objects. Constructors can be of two types.
Object 1. Parameterized Constructor
The object is an entity that has state and behavior. It
may be any real-world object like the mouse, 2. Non-parameterized Constructor
keyboard, chair, table, pen, etc.
 Creating the constructor in python
 Creating Classes and Objects The method the __init__() simulates the constructor
 Creating Classes of the class. This method is called when the class is
A class can be created by using the keyword class, instantiated. It accepts the self-keyword as a first
followed by the class name. The syntax to create a argument which allows accessing the attributes or
class is given below. method of the class.
Syntax Example
class Employee:
class ClassName:
def __init__(self, name, id):
#statement_suite
self.id = id
Example:
self.name = name
class Employee:
id = 10 def display(self):
name = "Devansh" print("ID: %d \nName: %s" % (self.id, self.name))
def display (self):
print(self.id,self.name) emp1 = Employee("John", 101)
emp2 = Employee("David", 102)
 Creating Object
A class needs to be instantiated if we want to use the # accessing display() method to print employee 1 information
class attributes in another class or method. A class emp1.display()
can be instantiated by calling the class using the # accessing display() method to print employee 2 information
class name.
emp2.display()
Syntax
Output:
<object-name> = <class-name>(<arguments>)
ID: 101
Example Name: John
class Employee: ID: 102
Name: David
id = 10
name = "John"
def display (self):
print("ID: “,self.id)
print("Name: “,self.name))
# Creating a emp instance of Employee class
emp = Employee()
emp.display()

4 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

 Classes with Multiple Objects print("Enter values of object 1 ")


We can also create multiple objects from a single obj1.GetNum()
class. For example. print("Enter values of object 2 ")
# define a class obj2.GetNum()
class Employee: print("Values of object 1 ")
# define an attribute obj1.PutNum()
employee_id = 0 print("Values of object 2 ")
obj2.PutNum()
# create two objects of the Employee class obj3 = obj1.Add(obj2)
employee1 = Employee() print("Values of object 3 (sum object) ")
employee2 = Employee() obj3.PutNum()

# access attributes using employee1 Output:


employee1.employeeID = 1001
print("Employee ID:", employee1.employeeID) Enter values of object 1
Enter value of x : 43
Enter value of y : 65
# access attributes using employee2 Enter values of object 2
employee2.employeeID = 1002 Enter value of x : 34
Enter value of y : 65
print("Employee ID:", employee1.employeeID)
Values of object 1
Output value of x = 43 value of y = 65
Values of object 2
value of x = 34 value of y = 65
Employee ID: 1001
Values of object 3 (sum object)
Employee ID: 1002
value of x = 77 value of y = 130

 Objects as Arguments, Objects as Return  Inheritance


Inheritance - acquiring properties of super class into
Values
sub class. It is also called as base- derived class or
Python allows its programmers to pass objects to
parent-child class.
method. And also return objects from a method.
Here is a program to illustrate this, Syntax
class TwoNum: class derived-class(base class):
def GetNum(self): <class-suite>
self.__x = int(input("Enter value of x : "))  Single and Multiple Inheritance
self.__y = int(input("Enter value of y : ")) Single Inheritance Single inheritance allows a
derivate class to inherit properties of one parent
def PutNum(self): class, and this allows code reuse and the introduction
print("value of x = ", self.__x,"value of y = ", of additional features in existing code.
self.__y, )

def Add(self,T):
R=TwoNum()
R.__x=self.__x+T.__x
R.__y=self.__y+T.__y
return R

obj1 = TwoNum()
obj2 = TwoNum()

5 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

Example: Example:
class Parent1:
class Calculation1:
def func1(self):
print ("function is defined inside the parent class.") def Summation(self,a,b):
return a+b;
class Child1(Parent1):
def func2(self): class Calculation2:
print ("function is defined inside the child class.") def Multiplication(self,a,b):
# Driver's code return a*b;
object = Child1()
object.func1() class Derived(Calculation1,Calculation2):
object.func2() def Divide(self,a,b):
return a/b;
Output: d = Derived()

function is defined inside the parent


print(d.Summation(10,20))
class. print(d.Multiplication(10,20))
function is defined inside the child print(d.Divide(10,20))
class.

Output:
Multiple Inheritance If a class is able to be created
30
from multiple base classes, this kind of Inheritance is 200
known as multiple Inheritance. When there is multiple 0.5
Inheritance, each of the attributes that are present in the
classes of the base has been passed on to the class that is  Multilevel and Multipath Inheritance
derived from it. Multi-level inheritance is archived 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 Base1:
<class-suite>
class Base2:
<class-suite> Syntax
. class class1:
. <class-suite>
. class class2(class1):
class BaseN: <class suite>
<class-suite> class class3(class2):
class Derived(Base1, Base2, ...... BaseN): <class suite>
<class-suite> .
.

6 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

Example # Derivied class2


class Animal: class Child_2(Parent1):
def speak(self): def func_3(self):
print("Animal Speaking") print ("This function is defined inside the child 2.")
#The child class Dog inherits the base class Animal
class Dog(Animal): # Driver's code
def bark(self): object1 = Child_1()
print("dog barking") object2 = Child_2()
#The child class Dogchild inherits another child class Dog object1.func_1()
class DogChild(Dog): object1.func_2()
def eat(self): object2.func_1()
print("Eating bread...") object2.func_3()
d = DogChild()
d.bark() Output:
d.speak() This function is defined inside the parent
d.eat() class.
This function is defined inside the child 1.
This function is defined inside the parent
Output: class.
This function is defined inside the child 2.
dog barking
Animal Speaking  Encapsulation
Eating bread...
This is the concept of wrapping data and methods
Multipath Inheritance that work with data in one unit. This prevents data
If multiple derived classes are created from the same modification accidentally by limiting access to
base, this kind of Inheritance is known as hierarchical variables and methods.
inheritance or Multipath Inheritance. In this instance, we  Private Instance Variables
have two base classes as a parent (base) class as well as  Class members who have been declared private
two children (derived) classes. should not be accessed by anyone outside the class
or any base classes. Python does not have Private
instance variable variables that can be accessed
outside of a class.
 To define a private member, prefix the member's
name with a double underscore "__".
Example:
class Base1:
class Parent1: def __init__(self):
def func_1(self): self.p = "Javatpoint"
print ("This function is defined inside the parent class.") self.__q = "Javatpoint"
# Creating a derived class
# Derived class1 class Derived1(Base1):
class Child_1(Parent1): def __init__(self):
def func_2(self): # Calling constructor of
print ("This function is defined inside the child 1.") # Base class

7 KLE’s BCA College, Chikodi


PYTHON PROGRAMMING UNIT IV

Please enter the value: Tpoint


Base1.__init__(self)
: JavaTpoint
print("We will call private member of base class")
print(self.__q)
# Driver code Example 2:
obj_1 = Base1()
print(obj_1.p) class complex_1:
def __init__(self, X, Y):
Output:
self.X = X
Javatpoint self.Y = Y

 Polymorphism # Now, we will add the two objects


Polymorphism refers to having multiple forms. def __add__(self, U):
Polymorphism is a programming term that refers to return self.X + U.X, self.Y + U.Y
the use of the same function name, but with different
signatures, for multiple types.
Object_1 = complex_1(23, 12)
 Operator Overloading Object_2 = complex_1(21, 22)
The operator overloading in Python means
Object_3 = Object_1 + Object_2
provide extended meaning beyond their
print (Object_3)
predefined operational meaning.
Such as, we use the "+" operator for adding two
Output:
integers as well as joining two strings or
merging two lists.
(44, 34)

Example 1:

class example:
def __init__(self, X):
self.X = X

# adding two objects


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)

Output:

Please enter the value: 23


Please enter the value: 21
: 44
Please enter the value: Java

8 KLE’s BCA College, Chikodi

You might also like