Python Unit 4
Python Unit 4
Python Unit 4
UNIT:4
FILE OPERATIONS:
Files are named locations on disk to store related information. They are used to permanently store data in a non-
volatile memory (e.g. hard disk).
Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we
usefiles for future use of the data by permanently storing them.
When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so
that the resources that are tied with the file are freed.
Hence, in Python, a file operation takes place in the following order:
1. Open a file
2. Read or write (perform operation)
3. Close the file
Opening Files in Python
Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is
used to read or modify the file accordingly.
F = open("myfile.txt")
We can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or append a
to the file. The default is reading in text mode. In this mode, we get strings when reading from the file.
MODE DESCRIPTION
r
Opens a file for reading. (default)
w
Opens a file for writing. Creates a new file if it
does notexist or truncates the file if it exists.
x
Opens a file for exclusive creation. If the file
already exists,the operation fails.
a
Opens a file for appending at the end of the file
withouttruncating it. Creates a new file if it does
not exist.
b
Opens in binary mode.
+
Opens a file for updating (reading and writing)
Example-2:
F = open("Demo.txt",'r')
print(F.read()) F.close()
Output-2:
WELCOME TO
CSE. WELCOME
TO ALL.
Good Luck!
Example-3:
F = open("Demo.txt",'r')
print(F.readlines()) F.close()
Output-3:
['WELCOME TO CSE.\n', 'WELCOME TO ALL.\n', 'Good Luck!']
Here, readlines() method read all lines in the form of list.
Output:
Here output will added at the end of Demo.txt file.
Here, file1 is created as object for MyFile1 and file2 as object for MyFile2.
Closing a file
close() function closes the file and frees the memory space acquired by that file. It is used atthe time when the file is
no longer needed or if it is to be opened in a different file mode.
Syntax:
File_object.close()
File_object.read([n])
readline() : Reads a line of the file and returns in form of a string.For specified n, reads at most n byte
However, does not reads more than one line, even if n exceeds the length of the line.
File_object.readline([n])
readlines() : Reads all the lines and return them as each line a string element in a list.
File_object.readlines()
Example:
# Program to show various ways to# read data from a file
# Creating a file
file1 =open("myfile.txt", "w")
L =["This is Delhi \n", "This is Paris \n", "This is London \n"]# Writing data to a file
file1.write("Hello \n")file1.writelines(L)
file1.close() # to change file access modesfile1 = open("myfile.txt", "r+") print("Output of Read function is ")
print(file1.read())
print()
# seek(n) takes the file handle to the nth# bite from the beginning.
file1.seek(0)
print("Output of Readline function is ")print(file1.readline())
print() file1.seek(0)
# To show difference between read and readlineprint("Output of Read(9) function is ") print(file1.read(9))
print() file1.seek(0)
print("Output of Readline(9) function is ")print(file1.readline(9))
print()
file1.seek(0)
# readlines function
print("Output of Readlines function is ")
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function isHello
This is Delhi This is Paris This is London
The open() function returns a file object. And the file object has two useful methods for writing text to the file:
write() and writelines().
The write() method writes a string to a text file and the writelines() method write a list of strings to a file at on
In fact, the writelines() method accepts an iterable object, not just a list, so you can pass a tuple of strings,
a set of strings, etc., to the writelines() method.
To write a line to a text file, you need to manually add a new line character:
f.write('\n') f.writelines('\n')
Code language: JavaScript (javascript)
And it’s up to you to add the new line characters.
Writing text file examples
The following example shows how to use the write() function to write a list of texts to a text file:
lines = ['Readme', 'How to write text files in Python'] with open('readme.txt', 'w') as f:
for line in lines:
f.write(line)
f.write('\n')
Python File writelines() Method
❮ File Methods
Example
Open the file with "a" for appending, then add a list of texts to append to the file:
f.close()
#open and read the file after the appending: f = open("demofile3.txt", "r") print(f.read())
OUTPUT:
Hello! Welcome to demofile2.txt This file is for testing purposes.
Good Luck!See you soon!Over and out.
Syntax: file.writelines(list)Example
The same example as above, but inserting line breaks for each list item:
f = open("demofile3.txt", "a")
f.writelines(["\nSee you soon!", "\nOver and out."])f.close()
If the file is only opened for writing in append mode using 'a', this method is essentially a no-op, but it rem
useful for files opened in append mode with reading enabled (mode 'a+').
If the file is opened in text mode using 't', only offsets returned by tell() are legal. Use of other offsets ca
undefined behavior.
Note that not all file objects are seekable.
Syntax
Following is the syntax for seek() method −
fileObject.seek(offset[, whence])
EXAMPLE:
# Python program to demonstrate# seek() method
# Opening "GfG.txt" text filef = open("GfG.txt", "r")
# Second parameter is by default 0 # sets Reference point to twentieth# index position from the beginningf.seek(20)
# prints current positionprint(f.tell())
print(f.readline())f.close()
OUTPUT:
20
When you have to explain it, it’s bad.
Example 2: Seek() function with negative offset only works when file is opened in binary mode. Lesuppose the binary
file contains the following text.
b'Code is like humor. When you have to explain it, its bad.'
# Python code to demonstrate# use of seek() function
Data member: A class variable or instance variable that holds data associated with a class and its objects.
Class variable: A variable that is shared by all instances of a class. Class variables are defined within a class but
outside any of the class's methods. Class variables are not used as frequently as instance variables are.
Instance variable: A variable that is defined inside a method and belongs only to the current instance of a class.
Function overloading: The assignment of more than one behaviour to a particular function. The operation performed
varies by the types of objects or arguments involved.
Inheritance: The transfer of the characteristics of a class to other classes that are derived from it.
Method: A special kind of function that is defined in a class definition.
Encapsulation: Using OOP in Python, we can restrict access to methods and variables. This prevents data fromdirect
modification which is called encapsulation. In Python, we denote private attributes using underscore as the prefix i.e
single _ or double.
CONCEPT OF CLASS:
A class is created with the keyword class and then writing the ClassName. The simplest form of class definition looks like
this:
Syntax:
class ClassName:
statement-1statement-2
.
.
<statement-N>
Class definitions, like function definitions (def statements) must be executed before they have any effect.
Example: class Student:
def _ _init_ _(self):
self.name="Mothi" self.branch="CSE" def display(self):
print("Name is",self.name) print("Branch is",self.branch)
Here, _ _init_ _ is a constructor and display is a method.
When we run the above program, it won’t give any output. Because, we didn’t use the class. To use this class we haveto
create and object and call the method.
To use this class we have to create and object and call the method.
OBJECTS AND INSTANCES:
To create an object, the following syntax is used:
objectName = ClassName( )
So, to create an object to Student class, we can write as:
s1 = Student()
To call the display method, we can write as:
s1.display()
When creating the object the following steps takes place internally:
First of all, a block of memory is allocated on heap. How much memory is to be allocated is decided from the
attributes and methods available in the Student class.
After allocating the memory block, the special method by the name ‘ init (self)’ is called internally. This method
stores the initial data into the variables. Since this method is useful to construct the instance, it is called
‘constructor’.
Finally, the allocated memory location address of the instance is returned into ‘s1’ variable.
CONSTRUCTOR:
Constructors are generally used for instantiating an object. The task of constructors is to initialize (assign values) tothe
data members of the class when an object of class is created. In Python the init () method is called the constructor and
is always called when an object is created.
Syntax:
def init (self):
# body of the constructor
Types of constructors:
Default constructor: The default constructor is simple constructor which doesn’t accept any arguments. It isdefinition has
only one argument which is a reference to the instance being constructed.
Parameterized constructor: constructor with parameters is known as parameterized constructor. The parameterized
constructor take 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.
Example: class Student: def _ _init_ _(self,n,b):self.name=n
self.branch=b
def display(self):
print("Name is",self.name) print("Branch is",self.branch)s1 = Student("Mothi","CSE") s1.display()
Output:
Name is MothiBranch is CSE
ATTRIBUTES AND DESTRUCTOR:
Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process
by which Python periodically reclaims blocks of memory that no longer are in use is termed as Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's referencecount reaches zero.
An object's reference count changes as the number of aliases that point to it changes.
The del () method is a known as a destructor method in Python. It is called when all references to the object havebeen
deleted i.e when an object is garbage collected.
Syntax:
def del (self):
# body of destructor
Example:
class Employee:
def init (self):
print('Employee created.')def del (self):
print('Destructor called, Employee deleted.')obj = Employee()
del obj
Output:
Employee created.
Destructor called, Employee deleted.
Destructor:
Python deletes unneeded objects (built-in types or class instances) automatically to free the memory space. The process
by which Python periodically reclaims blocks of memory that no longer are in use is termed as Garbage Collection.
Python's garbage collector runs during program execution and is triggered when an object's referencecount reaches zero.
An object's reference count changes as the number of aliases that point to it changes.
The del () method is a known as a destructor method in Python. It is called when all references to the object havebeen
deleted i.e when an object is garbage collected.
Syntax:
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4
INHERITANCE:
Software development is a team effort. Several programmers will work as a team to develop software.
When a programmer develops a class, he will use its features by creating an instance to it. When another programmer
wants to create another class which is similar to the class already created, then he need not create theclass from the
scratch. He can simply use the features of the existing class in creating his own class.
Deriving new class from the super class is called inheritance.
The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined inthe
child class.
A child class can also override data members and methods from the parent.
Syntax:
class Subclass(BaseClass):
<class body>
When an object is to SubClass is created, it contains a copy of BaseClass within it. This means there is a relation
between the BaseClass and SubClass objects.
We do not create BaseClass object,but still a copy of it is available to SubClass object.
Deriving one or more sub classes from a single base class is called ‘single inheritance’. In single inheritance, we always
have only one base class, but there can be n number of sub classes derived from it. For example, ‘Application_1’ is a
single base class from where we derive ‘Application_2’as sub class. This is called single inheritance.
Example:
class Application_1:
def chat(self):
print("Message Chatting !")
class Application_2(Application_1):
def chat(self):
super().chat()
print("Emogies Chatting !")
a2=Application_2()a2.chat()
Output:
Message Chatting !
Emogies Chatting. !
Multiple inheritance
Deriving sub classes from multiple (or more than one) base classes is called ‘multiple Inheritance’. All the members of
super classes are by default available to sub classes and the sub classes in turn can have their own members.
The best example for multiple inheritance is that parents are producing the children and the children inheriting the
qualities of the parents.
Example:
class Application_1:
def chat(self):
print("Message Chatting !")
class Application_2:
def chat(self):
print("Emogies Chatting !")
class Application_3(Application_1,Application_2):
def chat(self):
super().chat()
print("Images/Videos Chatting !")
a3=Application_3()a3.chat()
Output:
Message Chatting !
Images/Videos Chatting !
Here, only Application_1 chat() method will be executed, Application_2 chat() method will not be executed. In multiple
inheritance if two super classes will have same method name then only first super class methodwill be executed.
Problem in Multiple inheritance:
If the sub class has a constructor, it overrides the super class constructor and hence the super class constructor isnot
available to the sub class.
But writing constructor is very common to initialize the instance variables.
In multiple inheritance, let’s assume that a sub class ‘C’ is derived from two super classes ‘A’ and ‘B’ having their
own constructors. Even the sub class ‘C’ also has its constructor.
Multilevel Inheritance
Deriving one sub classes from a single base class and deriving another sub class one sub class is called ‘Multilevel
inheritance’.
!
Method Overloading:
Python does not support method overloading by default. But there are different ways to achieve method overloading in
Python. The problem with method overloading in Python is that we may overload the methods but can only use the latest
defined method.
To overcome the problem we can use the following method.
Overloading Operators:
Python operators work for built-in classes. But the same operator behaves differently with different types. For example, the +
operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.This feature in Python
that allows the same operator to have different meaning according to the context is called operator overloading.
So what happens when we use them with objects of a user-defined class? Let us consider the following class, whichtries to
simulate a point in 2-D coordinate system.
Example:
class Demo:
def init (self, x=0, y=0):
self.x = xself.y = y
d1 = Demo(1, 2)d2 = Demo(2, 3)print(d1+d2) Output:
Traceback (most recent call last):
File "C:/Python36-32/OPER_overload.py", line 7, in <module>print(d1+d2)
TypeError: unsupported operand type(s) for +: 'Demo' and 'Demo'
It shows an error, because we are performing addition operation on objects.
In Python, there is a special functions with double underscore _ _.Suppose we want the print() function to print thecoordinates
of the Demo object instead of what we got. We can define a str () method in our class that controls how the object gets printed.
Let's look at how we can achieve this:
Example:
class Demo:
def init (self, x=0, y=0):
self.x = xself.y = y
def str (self):
return "{0} {1}".format(self.x, self.y)d1 = Demo(1, 2)
print(d1)
d2 = Demo(2, 3)print(d2) Output:
12
23
Overloading + operator:
To overload the + operator, we will need to implement add () function in the class. With great power comes great
responsibility. We can do whatever we like, inside this function. But it is more sensible to return a Demo object of the
coordinate sum.
class Dog:
In this case, you have a (mostly empty) Dogclass, but no object yet. Let'screate one!
Instantiating objects
To instantiate an object, type the class name, followed by two brackets. Youcan assign this to a variable to keep
track of the object.
ozzy = Dog()
self.name = name
self.age = age
To access an object's attributes in Python, you can use the dot notation. This is done by typing the name of the
object, followed by a dot and the attribute'sname.
print(ozzy.name)
print(ozzy.age)
Ozzy
The bark method can now be called using the dot notation, after instantiating a new ozzy object. The
method should print "bark bark!" to the screen.
Notice the parentheses (curly brackets) in .bark(). These are always used when calling a
method. They're empty in this case, since the bark()methoddoes not take any arguments.
ozzy = Dog("Ozzy", 2)
ozzy.bark() bark bark!
class Dog:
pass
CLASS OBJECTS: An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of
the class with actual values. It’s not an idea anymore, it’s an actual dog, like a dog of breed pug who’s seven
years old. You can have many dogs to create many different instances, but without the class as a guide, you
would be lost, not knowing what information is required.
An object consists of :
State: It is represented by the attributes of an object. It also reflects theproperties of an object.
Behavior: It is represented by the methods of an object. It also reflects theresponse of an object to other objects.
Identity: It gives a unique name to an object and enables one object tointeract with other objects.
Python3 program to
VKR,VNB&AGK COLLEGE OF ENGINEERING
R20 Python unit4
Output:
mammal
I'm a mammalI'm a dog
In the above example, an object is created which is basically a dog named Rodger. This class only has two class
attributes that tell us that Rodger is a dogand a mammal.
The self
Class methods must have an extra first parameter in the method definition. We do not give a value for this
parameter when we call the method, Python provides it.
If we have a method that takes no arguments, then we still have to have one argument.
This is similar to this pointer in C++ and this reference in Java.
When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python
into MyClass.method(myobject, arg1, arg2)
– this is all the special self is about.
__init__ method
The __init__ method is similar to constructors in C++ and Java. Constructorsare used to initializing the object’s
state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at
the time of Object creation. It runs as soon as an object of a class is instantiated.The method is useful to do any
initialization you want to do with your object.
Python3
Output:
Hello, my name is Nikhil
Python3
# Python3 program to show that the variables with a value
# assigned in the class declaration, are class variables and# variables inside methods and constructors are instance
# variables.
# Class for DogclassDog:
# Class Variableanimal ='dog'
# The init method or constructordef init (self, breed, color):
# Instance Variableself.breed = breed self.color = color
# Objects of Dog class Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
print('Rodger details:') print('Rodger is a', Rodger.animal)print('Breed: ', Rodger.breed) print('Color: ', Rodger.color)
print('\nBuzo details:') print('Buzo is a', Buzo.animal)print('Breed: ', Buzo.breed) print('Color: ', Buzo.color)
# Class variables can be accessed using class# name also
print("\nAccessing class variable using class name")print(Dog.animal)
Output:
Rodger details:Rodger is a dogBreed: Pug Color: brown
Buzo details:
Buzo is a dog
Breed: BulldogColor: black
Accessing class variable using class nameDog
# main.py
print('What size pizza would you like? ') # prompts = input() # wait for input
d.set_size(s) # store input in data model
print(f'To confirm, you asked for a {d.get_size} pizza')
Add extra value to the data model
Our pizza program could be enhanced to get user input for a large number ofvariables. At the end of the prompting
section, we want to display all of the choices the user made back to them so they can visually confirm their order.
We can take advantage of the string built-in class method.
data.py
class Data(object):
_number_of_slices = int()
...
def _str_(self):
print(f'Size: {self.get_size()}')
print(f'Slices: {self.get_number_of_slices()}') print(f'Toppings: {self._get_toppings()}')
Case Study on ATM:
Program:
class ATM:
def init (self):self.balance=0.0
def check_balance(self): print("Balance is",self.balance)def deposit(self):
amount=float(input("Enter amount to deposit: "))if amount<=0:
print("Deposite amount should be greater than Zero")else:
self.balance+=amount print("Amount Deposited")def withdraw(self):
amount=float(input("Enter amount to withdraw: "))if amount<=0:
print("Withdraw amount should be grater than Zero")elif amount>self.balance:
print("Amount could not be withdrawn")else:
self.balance-=amount print("Amount Withdrawn")a1=ATM()
while True:
print("1.Balance Check 2.Deposit 3.Withdraw 4.Exit")ch=int(input("Enter Your Choice: "))
if ch==1: a1.check_balance()elif ch==2:
a1.deposit() elif ch==3: a1.withdraw()elif ch==4:
breakelse:
print("Invalid Choice")
Output:
1.Balance Check 2.Deposit 3.Withdraw 4.Exit Enter Your Choice: 1
Balance is 0.0
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 2
Enter amount to deposit: 500
Amount Deposited
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 1
Balance is 500.0
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 2
Enter amount to deposit: 500Amount Deposited
1.Balance Check 2.Deposit 3.Withdraw 4.ExitEnter Your Choice: 1
Balance is 1000.0
1.Balance Check 2.Deposit 3.Withdraw 4.Exit Enter Your Choice: 3
Enter amount to withdraw: 400Amount Withdrawn
Output
Output: