Python Unit4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

File handling

 A text file consists of human readable characters, which can be opened by


any text editor. On the other hand, binary files are made up of non-human
readable characters and symbols, which require specific programs to
access its contents
 A file is a named location on a secondary storage media where data are
permanently stored for later access. Mainly there are two types of files
Text and binary.
 A text file consists of human readable character and can be opened in
any text editor. Eg: .py, .txt, .csv etc
 A binary file consists of non-human readable character and symbols and
requires specific programs to access the contents. Eg: audio files, image
files, video files etc.

Steps : working with files


Step 1 : Opening file in python : To open a file in Python, we use the open()
function. The syntax of open() is as follows:
file_object= open(file_name, access_mode)
This function returns a file object called file handle which is stored in the
variable file_object. We can use this variable to transfer data to and from the
file (read and write) by calling the functions defined in the Python’s io module.
Table : Some File-modes

File Meaning File offset position


mode

r Read a file.If not present an error is Beginning of the file


thrown

w Write mode, If not present a new file is Beginning of the file


created. Otherwise the old one is
overwritten

wb Write a binary file. Beginning of the file

rb Read a binary file Beginning of the file

a Opens the file in append mode. If not End of the file


present then a new file is created

ab Opens the binary file in append mode. End of the file


If not present then a new file is created
Step 2 : Read form or write into the file by using the functions available such as
read(), readline or write(), writelines etc. The syntax is as follows:
file_object.method_name()

Step 3 : After readind or writing is done it is important to close the file. Python
provides a close() method to do so. While closing a file, the system frees the
memory allocated to it. The syntax of close() is:
file_object.close()

Alternatively
one can also open a file using with clause. The syntax of with clause is:
with open (file_name, access_mode) as file_ object:
The rest remains the same. The only advantage here is that the file closes
automatically onces the conrol comes outside the with clause
Example 1 : When using open() method.
Write a program to create a file name myfile.txt and write the following content
Hello word Let’s learn a thing or two about file handling.

Code :

A file name my_file.txt is created at the loction /home/shaan on successful


execution of the above program.

Output : file named my_file.txt displaying its contents


Example 2 :
considering the same example but now using with clause

Code :

A file name my_newfile.txt is created at the loction /home/shaan on successful


execution of the above program.

Output: file named my_newfile.txt displaying it’s contents

Note :
Observe the above two codes you will notice that when open() method is used
we need to close the file by using the close() method. But this is not the case
when we use with clause to open a file.

Working with text file :


Operations that can be performed :
 read
 write
 append
write operation
Open the file in write mode. If the file is already there then all the contents is
replaced by new one. If the file is not in the directory then a new file is created.
Method used :
 write() ---> To write single line (ref example 1 and 2)
 writelines() ---> To write multiple lines

writelines() method :
Example 3:

Note : you can use objects like string or tuples to store multiple string and then
pass the string object to the writeline method

append() method
is used to append the data at the end of the previous data if an existing file is
opened in append mode. Otherwise a new file is created if not present in the
directory.

Example 4: In our example we have opened an exising file newFile2.txt


(created in example 3) in append mode and have written a new line ‘I am fine
too..!!!
Read operation
It is used to read the contents of a an already existing file by openning in read
mode. If file is not present then an error is generated

Mehod used :
read(n) ---> read all the contents of a file and return a string
readline(n) ---> it is used to read single line in a file. It returns a string
readlines() ---> it is used to read all the lines in a file and returns list of string.

Consider the file myfile.txt having the following content


Now we will read myfile.txt file by using the above methods

Note : contents in r is in form of string if read() method is used

Note : contents in r is in form of string if readline() method is used and it reads


only the first line of the text file
Note : It reads all the lines and return list of strings

Binary Files
In order to work with binary file one need to import pickle module first and then
can use dump() or load() method to perform write and read operations
respectively.

Syntax to import pickle module :


import pickle

The dump() method converts the python object to write the data into a binary
file. This process is called pickling. The file in which data is to be dumped is
opened in binary write mode (wb)

Syntax:
pickle.dump(data_object ,file object)
Example : program to write data in binary file
Now if you open this file in any text editor it is non human readable format i.e.
the data is not understandable by us. See what we have entered and how the
data is shown in word file. Definetly not in a way it is written.

The load() method is used to load data from binary file. This process is called
unpickling. The file to be loaded is opened in binary read mode.

Syntax :
data_variable = pickle.load(file_object)
Example : To read data from binary file student.dat

CSV file (Comma Separated Values)


One of the most common ways to save data in tabular format. It must be saved
with .csv extension.
In order to work with csv file one has to import csv module.
Syntax to import csv module :
import csv
writing data into a CSV file
To write a data in csv file we use writer() function that returns a writer object
which converts the data into deliminated string. After that we can go with
writerow() method to write one row at a time or can use writerows() method
to write multiple rows at one go.

Syntax :
writer_object = csv.writer(file_object)
writer_object.writerow( single_record_object )
writer_obkect.writerows(multiple_records_object)

Example:

A file com_found.csv is being created having following details as shown in the


figure below

com_found.csv when viewed on text edior


com_found.csv when viewed on spreedsheet

another way of writing data into a csv file

import csv
with open('com_found.csv','w') as csv_w :
data = [[101,'Tim','Apple'],[102,'Bill','Microsoft'],[103,'Mark','Facebook'],
[105,'Elon','Tesla']]
write_data = csv.writer(csv_w)
write_data.writerows(data)
Reading data from a csv file
To reader a data from a csv file we use reader() function which returns an
iterable reader object which is then iterated using a for loop to print the data
row wise
Syntax :
reader_object = csv.reader(file_object)
Example : Reading data from com_found.csv file
Class
It provides a way to build data and functionality together. Python uses the keyword class to
define a class

Syntax:
class class_name :
class_members

A class contains class variables and methods, together known as class members which can
be accessed through objects which is an instance of a class.
Example

Accessing class members


To access class members, one needs to create an object and then using that object the
members are accessed.
Syntax: creating an object
Object_name = class_name()
Syntax: accessing class member
Object_name.class_variable
Object_name.method()
Example

Note:

• methods use first argument as self which refers to the object itself (object that has
called the method). So even if the methods take no argument, it should take first
argument as self.

• Classes provides a way to organize data and methods together into a structure that
prevents data access by a function that is not specified in the class. The integrity of the
data contained in the object is ensured by defining different access levels for data
variables and methods

• Any data or function with access level as public can be accessed by any function
belonging to any class.

• Any data or function with access level as private can be accessed only by the class in
which it is declared. Private variables are prefixed with double underscore ( __ ) .
eg __a1
Accessing private class variable like public class variable

Accessing private method like public method

Note: the above code generated an error as private members cannot be accessed like
public one outside the class.

How private class members are accessed

Syntax:
Object_name._class_name__class_variable
Object_name._class_name__method()
Example

Accessing class variables (public or private) within a class


The __init__() method (Constructor)

This method automatically executes when an object of a class is created and is useful to
initialize the variables of a class objects

Syntax:

def __init__(self, args):


variable_initialization

Example
Calling class method from another method
Method Overloading

Method overloading - Class having same name but with different parameters.
Python does not support method overloading.

Inheritance

It is a phenomenon where a class acquires the properties of another class. The class which acquires
the properties is called the sub class or child class or derived class. And the class from which the
properties are being acquired is called the base class or parent class or super class.

Syntax:

Class SubClassName (BaseClassName):


Class_members

Note: Class members are class variables and methods (class methods)
Note:

• A is the super class or base class or parent class


• B is the sub class or child class or derived class and it inherits all the class members of its parent
class i.e., if not declared as private.
• So, to access these class members (inherited once apart from class members B) we just need to
create the instance (Object) of class B.
Method overriding - If a subclass has the same method as declared in the parent class

Example
In our example the sub class B has same method display() as in its parent class A. Python invokes the
overridden method and thus Let Us Learn Python gets printed.

Types Of Inheritance

Multiple Inheritance

When a child class inherit features from more than one class.

Syntax:

class BaseClass1:
Class_members

class BaseClass2:
Class_members

class SubClass (BaseClass1, BaseClass2) :


Class_members

Example:

In the example given below Class C is inheriting the class members from Class A and Class B both of
them are super or base class. Note that class C has no members of its own.
Multilevel Inheritance

When a child class is inherits some features from a base class which is in-turn inheriting features
from some other class.

Syntax:

class BaseClass1:
Class_members

class SubClass1(BaseClass1):
Class_members

class SubClass2(SubClass1):
Class_members

Example:

In the example given below Class C is inheriting the class members of Class B and Class B is in-turn
inheriting from Class A. Therefore, Class C is also inheriting the properties of class A through its
parent class i.e., B
Multipath Inheritance

When a child class inherits some features from more than one base class which is in-turn inheriting
features from some other class.

Syntax:

class BaseClass:
Class_members

class SubClass1(BaseClass):
Class_members

class SubClass2(BaseClass):
Class_members

class SubCLass3(SubClass1, SubClass2):


Class_members

Example:

Multipath inheritance suffers from Diamond Problem where a derived class inherits member of the
base class (grandparent) twice via Subclass1 and Subclass2, which results in ambiguity and this must
be avoided. To avoid this problem python uses dynamic algorithm which linearizes the search order
in such a way that left-to-right ordering Is preserved and each parent is called only once.

In our example Class D is inheriting the properties class A twice via Class B and Class C which will result
into to ambiguity i.e. There exist two possible paths through which Class D can access the members
of Class A, one via Class B and the other via Class C. for example if you are calling the method display1()
it will result into ambiguity because it is unclear whether you calling the overridden method form B or
C. So, to avoid this problem python uses method resolution order (MRO) and the first name takes the
precedence. So here the overridden method from B will be considered as we have specified B first in
D (B, C).

Abstract Class

An abstract class is an interface definition and cannot be instantiated. It just servers as a template for
other classes by defining list of methods that the other class must implements i.e.; These classes lay
the foundation of other class that exhibits common behavior. In python we use the
NotImplementedError() to restrict the instantiation of a class.

Example:

In the example given below an abstract class Shape is being created which is inherited by two classes
Square and Rectangle. These classes use the methods of the parent class and implements it in their
own way.
Note: Instantiating the Abstract class Shape and trying to access its methods will result in error
The __init__() method
• The __init__() method or the class constructor executes automatically when
an object of a class is created
• It is use to initial the variables of the class object. The method is prefixed
and suffixed by double underscore
• It is declared as follows __init__(self, [args,…..])
Example:

Example: Create a class rectangle having following details:


Data members: length, breath
Methods: Rectangle_Area() → to calculate the area of the rectangle.
Rectangle_Perimeter() → to calculate the perimeter of the rectangle
Example: Create a class square having following details:
Data members: length, breath
Methods: Square_Area() → to calculate the area of the square.
Square_Perimeter() → to calculate the perimeter of the square.
Now if you are implementing inheritance then __init__() method call behaves
in a different way.
Example: In our example class B is inheriting from class A and upon the
creation of class B object. B’s __init__() method is called.
Calling the base class constructor
If one wants to call the constructor of the parent class then the __init__()
method is prefixed with super keyword in the following way:
super.__init()
Example: When using single inheritance

Example - multilevel inheritance: Here we have used super keyword inside


class C. So, it will call its parent i.e., B’s constructor.
If you want to call the grandparent constructor i.e, A’s constructor you have to
write super.__init__() inside class B

Example - Multiple Inheritance: When a class is inheriting from more than one
class which are at the same level. Then the parent class __init__() method call
which is made inside the child class is resolved through method resolution order
(MRO). i.e, whichever class is written first at the time of implementing the
inheritance, that class __init__() method is called. In our example class A is
placed first. See, the statement Class C (A, B). So, A’s constructor will be called.
Object and class variable
Class variables are owned by the class and any change in the class variable is
reflected throughout. Whereas object variables are owned by the objects and
any change made in one object variable is not reflected in the other
Syntax for class and object variable:
Class variable:
Class_name.variable_name
Example:
A.a1
Object variable:
self.variable_name
Example:
Self.a2
The __del__() method
This method is called automatically when the object goes out of scope and all
the resources that the object was holding are returned back to the system.
One can also explicitly do the same by using del keyword
Static methods:
These are special methods. Functionality that belongs to a class but does not
require an object are placed in static method. These method does not use the
self variable and is defined using a built-in function named staticmethod
prefixed by a decorator @ which takes in a function add some functionality to it
and then returns it. Using the decorator is also called metaprogramming
because a part of program tries to modify another part of program at compile
time.
Syntax:
@staticmethod
def mehod_name(arguments):
statements
Example
ADT
Abstract data types (ADT) involves both data and operation.
Some examples of ADT other than class:
Stack ADT (Class implementation)
A stack ADT is LIFO (Last in First Out) order list with the following functions:
• stack() → creates a new stack which is empty.
• push() → insert an element at the top of the stack.
• pop() → deletes an element from the top of stack. If stack is empty or top
value is -1 then an underflow error occurs.
• peek() → gives the top element of the stack but does not deletes it.

Queue ADT (Class implementation)


A Queue ADT is FIFO (First in First Out) order list with the following functions:
• queue() → creates a new stack which is empty.
• enqueue() → insert an element to the rear of the queue.
• dqueue() → deletes an element from front of the queue. If queue is empty
or front and rear both are -1 then an underflow error occurs.
• peek() → gives the front element of the queue but does not deletes it.
Error:
It is a bug in a program which may cause to terminate the program abnormally.
Broadly classified into three types: Compile time Error, Logical Error and
Runtime Error
Compile Time Error:
Error occurring at compilation process i.e., here the source code is checked if it
is following all the rules laid out by the programming language. Two types of
errors fall into this category are syntax error and semantic error.
Syntax Error
Occurs when rules of programming languages are violated.
Example:

The above program generates syntax error as we have not used the correct
format while writing for statement i.e., we have not put colon at the end of for
statement.
Semantic Error
These types of errors are detected at compile time, and occurs when the
meaning of the statements is not according to the rules defined for the
programming language. For example, assigning variable to a literal etc.

5 = a is semantically incorrect.
Logical Error
These errors in the program causes it to operate incorrectly but does not
terminate the program abruptly.
Example: Write a program to convert meter into km.

In the above program a logical error occurs as the output which we have got is
not the intended one i.e., 0.0035. This happens because we have multiplied
meters by 1000 instead of dividing it by 1000 or multiplying it with 0.001.
Run-Time-Errors
Errors that occur at run time or during the execution of the program. Also known
as Exception and it disrupts the flow of program. Now if an exception arises it
must be handled otherwise the program will terminate and error message will
be generated.

In the code above there is an exception occurred which was not handled due to
which the program terminates abruptly displaying the appropriate message.
Now to handle these types of situation python provides try and except block so
that the program terminates normally. The code which can raise the exception
is placed inside the try block and the code which handles it is written inside the
except block.
Let us re-write the above code using try and except block and see how it is being
handled.

Now when the above code is evaluated the exception arises again but this time
it is been handled.
You can also use multiple except block or can write multiple exception in a
single block
Example: using multiple except block

Code snippet: When the terminal was interrupted by pressing stop button
Code snippet: When the user has provided the value

Code Snippet: When no value is given


Example: Using multiple exception in single block

Code Snippet: When the terminal was interrupted by pressing stop button

Code Snippet: When the user has provided a value


Code Snippet: When no Value is given
Raising an Error
One can intentionally raise an exception by using raise keyword
Syntax:
raise Exception_Name( args, traceback)
args and traceback are optional arguments, args specifies the value for
exception argument. If not specified then its value is None whereas traceback is
an object which gives us the stack trace from the point of an exception handler
down the call stack, to the point where exception was raised i.e., it gives us the
information about what and where things went wrong.
Example: In our example we are taking an input and checking if it is less than
10 or not. If it is then an error is raised and is handled

code snippet: showing the use of raise keyword


Note: Whenever the traceback report is generated it is recommended to read it
backwords
Example:

Start reading from bottom to top i.e., up to the point where exception was raised.
Code Snippet: Traceback Error as shown in Jupyter Notebook

In our example the bottom line shows the type of error generated in our case it
is ValueError and an appropriate message invalid literal for int() with base 10 is
displayed. This error is generated at line number 1 where the input must be
provided by the user and the user accidently press the enter key before
providing an appropriate value resulting into an error.

Start reading from bottom to top i.e., up to the point where exception was raised.
Code Snippet: Traceback error as shown in Spyder IDE
Assertion
Assertion is the statement that state a fact. These are simply Boolean statement
that checks whether a statement is true or false. If it is true then the program
does nothing and execute the next line otherwise an error is thrown and the
program stops. It is just a debugger tool that halts when an error occurs and
displays it. Python uses assert statement to use assertion condition in the
program.
Syntax:
assert condition
or
assert condition, error_message
The examples below show how to use assert statement in python. In our
example we are taking two values one for the numerator and the other for
denominator and we use assert statement to check if the denominator is not
equal to zero before the division operation is executed. If denominator is a non-
zero value the division is performed other wise an error is generated.
Example: Method 1: using the syntax: assert condition

code snippet: when denominator is 0


code snippet: When denominator is a non-zero value
Example 2: Method 2: using the syntax: assert condition, error_message

code snippet: when denominator is 0


code snippet: When denominator is a non-zero value

You might also like