KEMBAR78
C3 Py | PDF | Python (Programming Language) | Modular Programming
0% found this document useful (0 votes)
7 views33 pages

C3 Py

The document provides an overview of modules and packages in Python, explaining their definitions, types, and methods for reusing them. It details the development of programmer-defined modules and packages, as well as approaches for importing and reloading them. Additionally, it covers exception handling, including types of errors, definitions, and the process of converting technical error messages into user-friendly messages.

Uploaded by

Kumaran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views33 pages

C3 Py

The document provides an overview of modules and packages in Python, explaining their definitions, types, and methods for reusing them. It details the development of programmer-defined modules and packages, as well as approaches for importing and reloading them. Additionally, it covers exception handling, including types of errors, definitions, and the process of converting technical error messages into user-friendly messages.

Uploaded by

Kumaran K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

===============================================

Modules in Python
===============================================
Index
---------
=>Purpose of Modules
=>Definition of Module
=>Types of Modules
=>Number of Approaches to Re-use the Modules
a) By Using import statement
b) By Using from ... import statement
=>Programming Examples
=>Re-Loading the Modules
=>Programming Examples
-------------------------------------------------------------------------------------------------------
=============================================
Modules in Python
=============================================
=>We know that Functions concept makes us to understand How to perform
operations and we can re-use within the same program but not able to re-use the
functions across the programs.
=>To reuse the functions and global variables across the programs, we must use
the concept of MODULES.
---------------------------------------
=>Definition of Module:
---------------------------------------
=>A Module is a collection of variables (global variables) , Functions and Classes.
-----------------------------------
=>Types of Modules:
-----------------------------------
=>In Python Programming, we have two types of Modules. They are
1) Pre-defined (or) Built-in Modules
2) Programmer or user or custom-defined modules.
-----------------------------------------------------
1) Pre-defined (or) Built-in Modules:
----------------------------------------------------
=>These modules are developed by Python Language Developers and they are
avialable in Python Software (APIs) and they are used python programmers for
dealing with Universal Requirements.

Examples: math cmath functools sys calendar os


re threading pickle random.......etc
=>Out of many pre-defined modules, in python programming one implicit pre-
defined module imported to every python program called "builtins" .
--------------------------------------------------------------------------------------------------------
2) Programmer or user or custom-defined modules:
---------------------------------------------------------------------------------------
=>These modules are developed by Python Programmers and they are avialable
in Python Project and they are used by other python programmers who are in
project development to deal with common requirements.
=>Examples:- aop mathsinfo icici ......etc
--------------------------------------------------------------------------------------------------------
--
=================================================
Development of Programmer-Defined Module
=================================================
=>To develop Programmer-Defined Modules, we must use the following steps

Step-1 : Define Variables (Global variables)


Step-2: Define Functions
Step-3: Define Classes

=>After developing step-1, step-2 and step-3 , we must save on some file name
with an extension .py (FileName.py) and it is treated as module name.
=>When a file name treated as a module name , internally Python execution
environment creates a folder automatically on the name of __pycache__ and it
contains module name on the name of "filename.cpython-310.pyc ".
-------------------
Examples:
------------------
__pycache__ <-----Folder Name
-------------------------------------------
aop.cpathon-310.pyc <-------------------Module
Name
mathsinfo.cpython-310.pyc<--------------Module
Name
icici.cpython-310.pyc<----------------------Module
Name
----------------------------------------------
===============================================
Number of approaches to re-use Modules
===============================================
=>We know that A Module is a collection of variables, Functions and Classes.
=>To re-use the features(Variable Names, Function Names and Class Names ) of
module, we have 2 approaches.They are
1) By using import statement
2) By using from.... import statement.
---------------------------------------------------------------------------------------
1) By using import statement:
---------------------------------------------------------------------------------------
=>'import' is a keyword
=>The purpose of import statement is that "To refer or access the variable names,
function names and class names in current program"
=>we can use import statement in 4 ways.
-------------------
=>Syntax-1: import module name
-------------------
=>This syntax imports single module
----------------
Example: import icici
import aop
import mathsinfo
--------------------------------------------------------------------
=>Syntax-2: import module name1, module name2....Module name-n
-------------------
=>This syntax imports multiple modules
----------------
Example: import icici , aop, mathsinfo
--------------------------------------------------------------------------------------------------------
--------------------
=>Syntax-3: import module name as alias name
-------------------
=>This syntax imports single module and aliased with another name
----------------
Example: import icici as i
import aop as a
import mathsinfo as m
--------------------------------------------------------------------------------------------------------
--------------------
=>Syntax-4: import module name1 as alias name, module name2 as alias
name......module name-n as alias name
-------------------
=>This syntax imports multiple modules and aliased with another names
----------------
Example: import icici as i, aop as a , mathsinfo as m
=>Hence after importing all the variable names, Function names and class names
by using "import statement" , we must access variable names, Function names
and class names w.r.t Module Names or alias names.
Module Name.Variable Name
Module Name.Function Name
Module Name.Class Name
(OR)
Alias Name.Variable Name
Alias Name.Function Name
Alias Name.Class Name

==============================================================
==============
2) By using from.... import statement.
=======================================
=>Here "form" "import" are the key words
=>The purpose of from.... import statement is that " To refer or access the
variable names, function names and class names in current program directly
without writing module name as alias name of Module name."
=> we can use from.... import statement in 3 ways.
-------------------
Syntax-1: from module name import Variable Names,Function Names, Class
Names
------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a
module.

Example: from calendar import month


from aop import addop,subop
from mathinfo import pi,e
from icici import bname,loc, calsimpleint

--------------------------------------------------------------------------------------------------------
---
Syntax-2: from module name import Variable Names as alias name,Function
Names as
alias name , Class Names as alias names.
-----------------------------------------------------------------------------------
=>This syntax imports the Variable Names,Function Names, Class Names of a
module with alias Names
Example: from calendar import month as m
from aop import addop as a,subop as s, mulop as m
from mathinfo import pi as p ,e as k
from icici import bname as b,addr as n , simpleint as si
--------------------------------------------------------------------------------------------------------
-------------
Syntax-3: from module name import *
---------------
=>This syntax imports ALL Variable Names,Function Names, Class Names of a
module.
=>This syntax is not recommmended to use bcoz it imports required Features of
Module and also import un-interrested features also imported and leads more
main memory space.

Example: from calendar import *


from aop import *
from mathsinfo import *

=>Hence after importing all the variable names, Function names and class names
by using "from ....import statement" , we must access variable names, Function
names and class names Directly without using Module Names or alias names.

Variable Name
Function Name
Class Name

=>Hence with "import statement" we can give alias name for module names only
but not for Variables Names, Function Names and Class Names. Where as with
"from ... import statement " we can give lias names for Variables Names, Function
Names and Class Names but not for Module Name.
=======================================X======================
===========
==========================================
realoding a modules in Python
==========================================
=>To reaload a module in python , we use a pre-defined function called reload(),
which is present in imp module and it was deprecated in favour of importlib
module.
=>Syntax:- imp.reload(module name)
(OR)
importlib.reload(module name) ----->recommended
----------------------------------
=>Purpose / Situation:
-----------------------------------
=>reaload() reloads a previously imported module.
=>if we have edited the module source file by using an external editor and we
want to use the changed values/ updated values / new version of previously
loaded module then we use reload().
===================================X==========================
============
#shares.py---file and treated as module name
def sharesinfo():
d={"Tech":19,"Pharma":11,"Auto":1,"Finance":00}
return d

#main program
#sharesdemo.py
import shares
import time
import importlib
def disp(d):
print("-"*50)
print("\tShare Name\tValue")
print("-"*50)
for sn,sv in d.items():
print("\t{}\t\t:{}".format(sn,sv))
else:
print("-"*50)
#main program
d=shares.sharesinfo()
disp(d)
time.sleep(15)
importlib.reload(shares) # relodaing previously imported module
d=shares.sharesinfo() # obtaining changed / new values of previously imported
module
disp(d)

Packages in Python
=========================================
Index
-----------
=>Purpose of Package
=>Definition of Package
=>Development of Package
=>Number of Approaches to re-use Packages
a) By Using sys.path.append()
b) By using PYTHONPATH Environmental Variable
=>Programming Examples
--------------------------------------------------------------------------------------------------------
-----------
Package in Python
=============================================
=>The Function concept is used for Performing some operation and provides
code re-usability within the same program and unable to provide code re-
usability across programs.

=>The Modules concept is a collection of Variables, Functions and classes and we


can re-use the code across the Programs provided Module name and main
program present in same folder but unable to provide code re-usability across
the folders / drives / enviroments.

=>The Package Concept is a collection of Modules.


=>The purpose of Packages is that to provide code re-usability across the
folders / drives / enviroments.

=>To deal with the package, we need to the learn the following.
a) create a package
b) re-use the package
--------------------------------------------------------------------------------------------------
a) create a package:
----------------------------
=>To create a package, we use the following steps.
i) create a Folder
ii) place / write an empty python file called __init__.py
iii) place / write the module(s) in the folder where is it
considered as Package
Name

Example:
--------------
bank <-----Package Name
-----------
__init__.py <----Empty Python File
simpleint.py <--- Module Name
aop.py-----Module Name
icici1.py---Module Name
welcome.py <--- Module Name
========================================================
b) re-use the package
---------------------------------
=>To the re-use the modules of the packages across the folders / drives /
enviroments, we have to two approaches. They are
i) By using sys module
ii) by using PYTHONPATH Environmental Variable Name
------------------------------------------------------------------------------------------
i) By using sys module:
-------------------------------------
Syntax:
----------- sys.path.append("Absolute Path of Package")

=>sys is pre-defined module


=>path is a pre-defined object / variable present in sys module
=>append() is pre-defined function present in path and is used for locating the
package name of python( specify the absolute path)

Example:

sys.path.append("E:\\KVR-PYTHON-6pM\\ACKAGES\\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-6PM\ACKAGES\BANK")
(or)
sys.path.append("E:\KVR-PYTHON-6PM/ACKAGES/BANK")
-----------------------------------------------------------------------------------------------
ii) by using PYTHONPATH Enviromental Variables:
------------------------------------------------------------------------
=>PYTHONPATH is one of the Enviromental Variable
=>Search for Enviromental Variable
Steps for setting :
------------------------------
Var name : PYTHONPATH
Var Value : E:\KVR-PYTHON-7AM\PACKAGES\BANK

The overall path


PYTHONPATH= E:\KVR-PYTHON-11AM\
PACKAGES\BANK
--------------------------------------------------------------------------------------

============================================
Exaception Handling
============================================
Index
---------
=>Purpose of Exception Handling
=>Types of Errors
i) Compile Time Errors
ii) Logical Errors
iii) Runtime Errors
=>Definition of Exception
=>Definition of Exception handling
=>Types of Exceptions.
a) Pre-defined Exceptions
b) Programmer-Defined Exceptions
=>Handling Exceptions
=>Keywords for Handling Exceptions
1. try
2. except
3. else
4. finally
5. raise
=>Syntax for Handling Exceptions
=>Programming Examples
---------------------------------------------------------------------
=>Development of Programmer-Defined Exceptions
=>Programming Examples
--------------------------------------------------------------------
=>ATM Case Study

================================================
Building Blocks of Exception Handling

================================================
1. When the application user or end user enters Invalid Input then we get Run
time Errors.
( Invalid Input----->Run time Error )
2. By default Runtime Erros always generates Technical Error Messages.
-------------------------------------
3. Definition of Exception: Every Runtime Error is called Exception
------------------------------------- ( Invalid Input---->Runtime Error------>Exception )
Hence Every Valid Input gives Result.
Every InValid Input gives Exception.

4. By default All exceptions gives Technical Error Messages.


-------------------------------------------------------
5. Definition of Exception Handling:
-------------------------------------------------------
=>The Process of converting Technical Error Messages into User-Friendly Error
Messages is
called Exception Handling

6. When Exception Occurs , Internally PVM perform 3 steps


a) PVM Ternimates the program execution Abnormally.
b) PVM comes out of Program flow
c) PVM generates Technical Error Message by default.

7. To Perform Step-(a),Step-(b) and Step-(c) by PVM, PVM creates an object of


appropriate
exception class .
8. When an exception occurs, PVM creates an object of appropriate
exception class. Hence Every Invalid Input gives Exception and Every Exception
considered as object of appropriate exception class
9. Hence Every Exception is python is Object of appropriate exception class.
==============================x===============================
======

================================================
Types of Errors in Exception Handling

================================================
=>The Purpose of Exception Handling is that " To Build Robust (Strong)
Applications ".
=>In Real Time, To develop any project, we must choose one programming
language and by using that language, we develop, compile and execute the
programs. During this process we get 3 types of Errors. They are

1. Compile Time Errors


2. Logical Errors
3. Runtime Errors
--------------------------------------------------------------------------------------------------------
------------------------
1. Compile Time Errors
--------------------------------------------------------------------------------------------------------
------------------------
=>Compile Time Errors are those which are occuring during Compilation Process.
=>Compile Time Errors occurs due to Syntaxes are not followed.
=>Compile Time Errors must be solved by Programmers at development time.
--------------------------------------------------------------------------------------------------------
------------------------
2. Logical Errors
--------------------------------------------------------------------------------------------------------
------------------------
=>Logical Errors are those which are occuring during Run time or Execution
Process.
=>Logical Errors occurs due to Wrong Representation of Logic.
=>Logical Errors gives Wrong Results or Inconsistent Results.
=>Logical Errors must be solved by Programmers at development time.
--------------------------------------------------------------------------------------------------------
------------------------
3. Runtime Errors ( Implementation Errors)
--------------------------------------------------------------------------------------------------------
------------------------
=>Runtime Errors are those which are occuring during Run time or Execution
Process.
=>Runtime Errors occurs due to Wrong or Invalid Input Entered by End User or
Application
User.
=>By default Runtime Error gives Technical Error Messages and these messages
Understandable by Programmers but not by End Users. So Industry is
recommended to generate User-Friendly Error Messages by using Exception
Handling.
--------------------------------------------------------------------------------------------------------
------------------
=================================
Handling the exception in Python
=================================
=>Handling the exception in Python is nothing but Coverting Technical Error
Messages into
User-Friendly Error Messages.
=>To do this convertion, In Python Programming we have 5 keywords. They are

1. try
2. except
3. else
4. finally
5. raise
--------------------------------------------------------------------------------------------------------
-----------
Syntax for handling the exceptions
--------------------------------------------------------------------------------------------------------
-----------
try:
Block of statements
Generating Exceptions
except <exception-class-name-1>:
Block of statetements generates
User-Friendly Error Messages
except <exception-class-name-2>:
Block of statetements generates
User-Friendly Error Messages
---------------------------------------------------
---------------------------------------------------
except <exception-class-name-n>:
Block of statetements generates
User-Friendly Error Messages
else:
Block of statetements generates
Results
finally:
Block of statetements executes
compulsorily
--------------------------------------------------------------------------------------------------------
-----------

Detailed Explanation of all Block---tomorrow


try block:
---------------

except

else

finally
=======================================
Types of Exceptions in Python
=======================================
=>In Python Programming, we have 2 types of exceptions. They are

1. Pre-Defined or Built-in Exceptions


2. Programmer / User / Custom-Defined Exceptions
---------------------------------------------------------
1. Pre-Defined or Built-in Exceptions
---------------------------------------------------------
=>These exceptions are defined and developed by Python Developers and they
are available as part of Python Software and used by python Programmers for
dealing Universal Problems.
=>Some of the Universal Problems are
a) Division by Zero ( ZeroDivisionError)
b) Invalid number format ( ValueError )
c) Invalid Indices ( IndexError)
d) Wrong module name (ModuleNotFoundError ).........etc
--------------------------------------------------------------------------------------------------------
----------------------
2. Programmer / User / Custom-Defined Exceptions
--------------------------------------------------------------------------------------------------------
----------------------
=>These exceptions are defined and developed by Python Programmers and they
are available as part of Python Project and used by other python Programmers
who are in the project for dealing with Common Problems.
=>Some of the Common Problems are
a) Attempting to enter Invalid PIN
b) Attemmpting to enter Wrong User Name and Password
c) Attempting to withdraw more amount than existing
...............................etc
--------------------------------------------------------------------------------------------------------
----------------------
=================================================
Explanation for the keywords in handling exceptions
=================================================
-----------
1) try:
-----------
=>It is the block in which we write block statements generates exceptions. In
otherwords, whatever the
statements are generating exceptions, those statements must written within
try block and try block is called exception monitering block.
=>When the exception occurs in try block then PVM Comes out of try Block and
executes appropriate
except block
=>After executing appropriate except block, PVM never goes to try block to
execute rest of the
statements.
=>Every try block must be immediately followed by except block (otherwise we
get SyntaxError)
=>Every try block must contain atleast one except block and recommended to
define / write multiple
except blocks for generating multiple user-friendly error messages.
-----------------
2)except
-----------------
1) It is the block in which we write block of statements gives User-Friendly Error
Messages. In
Otherwords, except block supresses the Technical error Messages and
Generates User-Freindly Erros Mesasges and this block is called Exception
Prcessing Block.

NOTE:- Handling Exception= try block + except block

2) except block will execute when there is an exception in try block.


3) Even we write multiple except block, PVM execute appropriate except block
depends on type of
exception occurs in try block.
4) The place of writing except block is after try block and before else block(if
present)
-----------------------
3. else
------------------------
1) It is the block, In which we define Block of statements generates results and
this block is known as
Result generated Block
2) else block will execute where is no exception in try block.

3) Writing else block is Optional


4) The place of writing else is after except block and before finally (if present)
--------------------------------
4. finally
---------------------------------
1. It is the Block, In which we block of statements used for Relinquishing (Close /
release / clean-up/
give-up) the Resources (Files, Databases) which are obtained in try block.
2. Writing / Defining finally Block is Optional
3. finally block will execute compulsorily (if we write)
4. The place of writing finally is after else block ( if it present)
==================================x===========================
=================
============================================
Various Forms of except blocks
============================================
=>except block contains Variouis Forms. They are
--------------------------------------------------------------------------------------------------------
-------------------------------------------
Form-1: This Syntax handle one exception at a time and generates user-friendly
Error message one
at a time.
--------------------------------------------------------------------------------------------------------
--------------------------------------------
Syntax: try:
----------------------
----------------------
except <exception-class-name>:
------------------------------------
------------------------------------

Examples: Refer Div2.py Program


-----------------------------------------------------------------------------------------------------
Form-2:The feature is called "Multi Exception Handling Block"
Here with Single except block, we can handle multiple specific
exceptions and generates multiple user-friendly error messges.
-----------------------------------------------------------------------------------------------------
try:
------------------------------------
------------------------------------
except (exceptio-class-1,exceptio-class-2,...exceptio-class-n):
-------------------------------------------
Multiple User-friendly Error Messages
------------------
Examples: Refer Div3.py Program
-----------------
-----------------------------------------------------------------------------------------------------
Form-3: Handling the Single Specific Exception with alias name
here alias name of exception can capture the Tech error of
corresponding exception.
-----------------------------------------------------------------------------------------------------
Syntax: try:
----------------------
----------------------
except <exception-class-name-1> as alias name:
------------------------------------
------------------------------------
except <exception-class-name-2> as alias name:
------------------------------------
------------------------------------
------------------
Examples: Refer Div4.py Program
-----------------
-----------------------------------------------------------------------------------------------------
Form-4 : default except block
=>This default block will execute when no exception matches with
exception exceptions.

Syntax: try:
----------------------
----------------------
except :
------------------------------------
------------------------------------
------------------
Examples: Refer Div5.py Program
-----------------

-----------------------------------------------------------------------------------------------------
Standard Syntax-1:
try:
Block of statements
Generating Exceptions
except <exception-class-name-1>:
Block of statetements generates
User-Friendly Error Messages
except <exception-class-name-2>:
Block of statetements generates
User-Friendly Error Messages
---------------------------------------------------
---------------------------------------------------
except <exception-class-name-n>:
Block of statetements generates
User-Friendly Error Messages
except : #default Exception block
default error messages
else:
Block of statetements generates
Results
finally:
Block of statetements executes
compulsorily
(OR)

ry:
------------------------------------
------------------------------------
except (exceptio-class-1,exceptio-class-2,...exceptio-class-n):
-------------------------------------------
Multiple User-friendly Error Messages

except : #default Exception block


default error messages
else:
Block of statetements generates
Results
finally:
Block of statetements executes
compulsorily

------------------
Examples: Refer Div6.py Program
-----------------

===================================x==========================
===========
=============================================
Development of Programmer-Defined Exceptions
=============================================
=>These exceptions are defined and developed by Python Programmers and they
are available as part of Python Project and used by other python Programmers
who are in the project for dealing with Common Problems.
=>Some of the Common Problems are
a) Attempting to enter Invalid PIN
b) Attemmpting to enter Wrong User Name and Password
c) Attempting to withdraw more amount than existing
...............................etc
--------------------------------------------------------------------------------------------------------
------------
=>Steps for Developing Programming Exceptions.
--------------------------------------------------------------------------------------------------------
------------
Step-1: Choose the Programmer-defined class name
Step-2: The Programmer-defined class name must Inherit from Base class
exception called "Exception
or BaseExeception"
Step-3: The above development must be saved on some file name with an
extension.py (Module
Name)
--------------------------------------------------------------------------------------------------------
------------------------------------
Example: class LoginError(Exception):pass
class InSuffBal(BaseException):pass
=>Here LoginError and InSuffBal are comes under Programmer-defined
Exception sub classses.
--------------------------------------------------------------------------------------------------------
------------------------------------
=================================================
raise key word
=================================================
=>raise keyword is used for hitting / raising / generating the exception provided
some condition must be satisfied.
=>raise keyword always used inside of Function Definition only.
=>PVM uses raise keyword implicitly for hitting pre-defined Exception where as
Programmer makes the PVM to use raise keyword explicitly for Hitting or
Generating Programmer-defined Exceptions.

=>Syntax:- if (Test Cond):


raise <exception-class-name>

=>Syntax:- def functionname(list of formal parms if any):


-----------------------------------------------------
-----------------------------------------------------
if (Test Cond):
raise <exception-class-name>
--------------------------------------------------------

Examples:
-------------------
from kvr import KvrDivisionError
def division(a,b):
if(b==0):
raise KvrDivisionError
else:
return (a/b)
-----------------------------------------------------------------------------
============================================
Data Persistenecy by Files of Python
============================================
-------------------
Def. of File:
-----------------------------------------------------
=>A File is a collection of Records.
=>Files Resides in Secondary Memory(HDD).
=>Technically, File Name is a named location in Secondary Memory.
-----------------------------------------------------
=>All the objects data of main memory becomes records in File of Secondary
memory and records of file of secondary memory becomes the objects in main
memory.
----------------------------------------------------
Def. of Stream:
----------------------------------------------------
=>The Flow of Data between object(s) of Main Memory and Files of Seconday
memory is called
Stream.
--------------------------------------------------------------------------------------------------------
--------------------------
=================================================
Types of Application in Files
=================================================
=>The purpose of Files in any programming language is that " To maintain Data
Persistency".
=>The Process of storing the data permanently is called Data Persistency.
=>In this context, we can develop two types of applications. They are
1) Non-Persistant Applications
2) Persistant Applications
=>In Non-Persistant Applications development, we read the data from Keyboard ,
stored in main memory(RAM) in the form objects, processed and whose results
displayed on Moniter.
Examples: ALL our previous examples comes under Non-Persistant
Applications.

=>We know that Data stored in Main Memory is temporary.

=>In Persistant Applications development, we read the data from Keyboard ,


stored in main memory(RAM) in the form objects, processed and whose results
stored Permanently.
=>In Industry, we have two ways two store the Data Permanently. They are
1) By using Files
2) By Using DataBase Softwares ( Oracle, MySQL,
MongoDB, DB2, PostgreySQL, SQL
Server,SQLITE3..etc)
=================================x============================
=========
============================================
Data Persistenecy by Files of Python
============================================
-------------------
Def. of File:
-----------------------------------------------------
=>A File is a collection of Records.
=>Files Resides in Secondary Memory(HDD).
=>Technically, File Name is a named location in Secondary Memory.
-----------------------------------------------------
=>All the objects data of main memory becomes records in File of Secondary
memory and records of file of secondary memory becomes the objects in main
memory.
----------------------------------------------------
Def. of Stream:
----------------------------------------------------
=>The Flow of Data between object(s) of Main Memory and Files of Seconday
memory is called
Stream.
--------------------------------------------------------------------------------------------------------
------------------
==============================================
Operations on Files
==============================================
=>On the files, we can perform Two Types of Operations. They are
1) Write Operation.
2) Read Operation.

1) Write Operation:
-----------------------------
=>The purpose of write operation is that " To transfer or save the object data of
main memory as record in the file of secondary memory".
=>Steps:
1) Choose the File Name
2) Open the File Name in Write Mode
3) Perform cycle of Write Operations.
=>While we are performing write operations, we get the following exceptions.
a) IOError
b) OSError
c) FileExistError
------------------------------
2) Read Operation:
------------------------------
=>The purpose of read operation is that " To transfer or read the record from file
of secondary memory into the object of main memory".
=>Steps
a) Choose the file name
b) Open the file name in Read Mode
c) Perform cycle of read operations.
=>While we performing read operations, we get the following exceptions.
a) FileNotFoundError
b) EOFError
================================x=============================
============
======================================
File Opening Modes
======================================
=>The purpose of File Opening Modes is that "In which type file mode we are
opening the file".
=>In Python Programming, we have 8 File Opening Modes. They are
1. r 2. w 3. a 4. r+ 5. w+ 6. a+ 7. x 8. x+
-----------------------------------------------------------------------------------------------
1) r
-----------------------------------------------------------------------------------------------
=>This mode is used for opening the file name in READ Mode.
=>If we open the file name in 'r' mode and if the file name does not exist then we
get
FileNotFoundError.
=>"r" mode is default mode of all file opening modes.
-----------------------------------------------------------------------------------------------
2) w
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "w" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "w" then EXISTING FILE Data
OVERLAPPED with new Data.
-----------------------------------------------------------------------------------------------
3) a
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "a" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "a" then EXISTING FILE Data APPENDED
with new Data.
-----------------------------------------------------------------------------------------------
4) r +
-----------------------------------------------------------------------------------------------
=>This mode is used for opening the file name in READ Mode.
=>If we open the file name in 'r+' mode and if the file name does not exist then we
get
FileNotFoundError.
=>With "r+" mode, First we Must read the data and Later we can perform Write
Operation.
--------------------------------------------------------------------------------------------------------
----------------------------------------
5) w +
--------------------------------------------------------------------------------------------------------
------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "w" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "w" then EXISTING FILE Data
OVERLAPPED with new Data.
=>With "w+" mode , Additionally we can perform Read Operation After
Performing Write Operation.
--------------------------------------------------------------------------------------------------------
-----------------------------------
6) a+
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and Opening the file name in WRITE
Mode always.
=>If we are opening NEW FILE in "a+" mode then that File Created Newly and
Opened in write mode
=>If we are opening EXISTING FILE in "a+" then EXISTING FILE Data APPENDED
with new Data.
=>With "a+" mode , Additionally we can perform Read Operation After
Performing Write Operation.
--------------------------------------------------------------------------------------------------------
--------------------------------------
7) x
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and exclusively Opening the file
name in WRITE Mode
always.
=>Once we open File Name in "x" mode , we can Perform Write Operations only.
=>If we open existing file in "x" mode then we get FileExistError
--------------------------------------------------------------------------------------------------------
------------------
8) x+
-----------------------------------------------------------------------------------------------
=>This mode is used for Creating File Name and exclusively Opening the file
name in WRITE Mode always.
=>Once we open File Name in "x+" mode , we can Perform Write Operations First
and Letter we can Perform Read Operations also
=>If we open existing file in "x+" then we get FileExistError
--------------------------------------------------------------------------------------------------------
------------------
=========================================
Opening Files
=========================================
=>To perform any type of Operation, we must open the file.
=>In Python Programming, To open the file, we have two approaches. They are
1. By using open()
2. By using " with open() as "
--------------------------------------------------------------------------------------------------------
-----------
1) By using open()
--------------------------------------------------------------------------------------------------------
-----------
=>Syntax: varname=open("File Name","File Mode")
--------------------
Explanation
--------------------
=>varname represents File Pointer and always points to the content of file and it
is an object of type TextIOWrapper
=>open() is one of the pre-defined Function, which is used for opening the
specified File Name
in Specified File Mode
=>File Name represents Name of the file
=>File Mode represents r,w,a,r+,w+,a+,x,x+
=>When we open the file with open() then it is recommended to close the file
manually by
using close(). In otherwords open() does not provide auto-closability of Files.

--------------------------------------------------------------------------------------------------------
-----------
2) By using " with open() as "
--------------------------------------------------------------------------------------------------------
-----------
Syntax:- with open("File Name","File Mode") as Varname:
----------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
----------------------------------------------------------
-------------------------------------------------------------------
Other statemenets out-of "with open() as " statements
--------------------------------------------------------------------

Explanation:
-------------------
=>Here "with" and "as" are are the key words
=>open() is one of the pre-defined Function, which is used for opening the
specified File Name
in Specified File Mode
=>varname represents File Pointer and always points to the content of file and it
is an object
of type TextIOWrapper
=>File Name represents Name of the file
=>File Mode represents r,w,a,r+,w+,a+,x,x+
=>The advantage of " with open() as " is that "Auto-Closability of File. In
Otherwords, as long as PVM is executing Indentation block of " with open() as "
then File Name is Active(Open) and Once PVM comes out-of Indentation block of
" with open() as" then File Name closed automatically (no need to use close() ).
==============================X===============================
==========
==============================================
Writing the data to the File
==============================================
=>To write the data to the file, we have 2 pre-defined Functions in file pointer
object. They are
1) write()
2) writelines()
--------------------------------------------------------------------------------------------------------
----------
1)write()
--------------------------------------------------------------------------------------------------------
----------
=>Syntax: filepointerobj.write(strdata)
=>This Function is used for writing any type of Data to the file in the form of str
=>Examples: refer FileWriteEx1.py
--------------------------------------------------------------------------------------------------------
----------
2)writelines()
--------------------------------------------------------------------------------------------------------
----------
=>Syntax: filepointerobj.writelines(Iterable-object)
=>This Function is used for writing any type of Iterable Object to the file in the
form of str
=>Examples: refer FileWriteEx2.py
--------------------------------------------------------------------------------------------------------
----------
==============================================
Reading the Data from File
==============================================
=>To read the data from the file, we have 2 pre-defined functions present File
Pointer object. They are
1) read()
2) readlines()
--------------------------------------------------------------------------------------------------------
------------------
1) read()
--------------------------------------------------------------------------------------------------------
------------------
=>Syntax:- varname=filepointerobj.read()
=>This Function is used for reading the entire data from file and placed in LHS
Varname in the form of
str.
----------------
Examples:
----------------
--------------------------------------------------------------------------------------------------------
------------------
2) readline()
--------------------------------------------------------------------------------------------------------
------------------
=>Syntax:- varname=filepointerobj.readlines()
=>This Function is used for reading the entire data from file the form of Line by
line and placed in LHS
Varname in the form of list object.
------------------
Examples:
------------------
--------------------------------------------------------------------------------------------------------
------------------
================================
Types of Files
================================
=>In Python Programming, we have two types of Files. They are
a) Text Files
b) Binary Files

1) Text File:
--------------------
=>A Text File always contains Alphabets, Digits and Special Symbols.
=>Text Files always denoted by a letter "t"
=>The default file in python is text file.
-------------------------------------------------------
Examples: .py .java .c .cpp .txt .doc....etc
-----------------------------------------------------------------------------------------------------
2) Binary File:
--------------------
=>A BinaryFile always contains Data in Binary Format ( Pixles)
=>Binary Files always denoted by a letter "b"

Examples: images (.jpg, .jpeg, .png, .gif)


audio and video files
PDF documents with Images.
-------------------------------------------------------------------------------------------------------
=================================================
Pickling and Un-Pickling
(OR)
Object Serialization or Object De-Serialization
=================================================
--------------
Pickling ( Object Serialization)
--------------
=>Let us assume there exist an object which contains multiple values. To
save or write object data of main memory into the file of secondary memory by
using write() and writelines() , they transfers the values in the form of value by
value and it is one of the time consuming process( multiple write operations).
=>To Overcome this time consuming process, we must use the concept of
Pickling.
=>The advantage of pickling concept is that with single write operation , we can
save or write entire object data of main memory into the file of secondary
memory.
=>Definition of Pickling:
---------------------------------
=>The Process saving or transfering entire object content of main memory into
the file of secondary memory by performing single write operation is called
Pickling.
=>Pickling concept participates in Write Operations.
-----------------------------------------------------------
Steps for implementing Pickling Concept:
-----------------------------------------------------------
=>import pickle module, here pickle is one of the pre-defined module
=>Choose the file name and open it into write mode.
=>Create an object with collection of values (Iterable object)
=>use the dump() of pickle module. dump() save the content of any object into
the
file with single write operation.
Syntax: pickle.dump(object , filepointer)
=>NOTE That pickling concept always takes the file in Binary Format.
--------------------------------------------------------------------------------------------------------
------
Un-Pickling (Object De-Serialization)
--------------------------------------------------------
=>Let us assume there exists a record with multiple values in a file of secondary
memory. To read or transfer the entire record content from file of secondary
memory, if we use read(), readlines() then they read record values in the form of
value by value and it is one of the time consuming process( multiple read
operations).
=>To overcome this time consuming process, we must use the concept of Un-
pickling.
=>The advantange of Un-pickling is that with single read operation, we can read
entire record content from the file of secondary memory into the object of main
memory.
=>Definition of Un-Pickling:
-------------------------------------------
=>The process of reading or trasefering the enrite record content from file of
secondary memory into the object of main memory by performing single read
operation is called Un-pickling.

=>Un-Pickling concept participates in Read Operations.


----------------------------------------------------------------
Steps for implementing Un-Pickling Concept:
-----------------------------------------------------------------
=>import pickle module
=>Choose the file name and open it into read mode.
=>Use the load() of pickle module. load() is used for transfering or loading the
entire record content from file of secondary memory into object of main
memory.
Syntax: objname=pickle.load(filepointer)
=>NOTE That Un-pickling concept always takes the file in Binary Format.
--------------------------------------------------------------------------------------------------------
---------
================================================
Working with CSV Files in Python
================================================
=>CSV stannds for Comma Separated Values.
=>A CSV File is one of the is a simple file format used to store tabular data, such
as a
spreadsheet or database.
=>A CSV file stores tabular data (numbers and text) in plain text.
=>Each line of the CSV file is a data record. Each record consists of one or more
fields,
separated by commas.
=>Python provides an in-built module called csv to work with CSV files.
=>There are 2 classes provided by this module for writing the data to CSV File.
They are
1) By using Using csv.writer class object
2) By Using csv.DictWriter class object
---------------------------------------------------
1) By using Using csv.writer class object
----------------------------------------------------
=>The csv.writer class object is used to insert data to the CSV file.
=>To create an object of csv.writer class object, we use writer() and present in
csv module.
=>csv.writer class object provides two Functions for writing to CSV file.
=>They are
1) writerow()
2) writerows()

1) writerow(): This Function writes a single row at a time.


Field row / Header can also be written using this Function.
Syntax:- csvwriterobj.writerow(fields Row / Data Row)
2) writerows(): This Function is used to write multiple rows at a time.
This can be used to write rows list.
Syntax: Writing CSV files in Python
csvwriterobj.writerows(data rows)
here data rows can be list, tuple set,frozenset only
--------------------------------------------------------------------------------------------------------
------
2) By Using csv.DictWriter class object
---------------------------------------------------------------
=>The csv.DictWriter class object is used to insert dict data to the CSV file.
=>To create an object of csv.DictWriter class object, we use DictWriter() and
present in csv module.
=>csv.DictWriter class object provides two Functions for writing to CSV.
1) writeheader()
2) writerows()
------------------------
1) writeheader():
------------------------
=>writeheader() method simply writes the first row of your csv file using the
pre-specified fieldnames.
Syntax: DictWriterObj.writeheader()
----------------------------------------------------------
2) writerows():
------------------------
=>writerows() method simply writes all the values of (Key,Value) from dict
object in the form of separate rows[ Note: it writes only the values(not keys) ]
Syntax:- DictWriterObj.writerows(dictobject)
--------------------------------------------------------------------------------------------------------
-----------------------
Reading the data from CSV File
--------------------------------------------------------------------------------------------------------
----------------------
=>There are various ways to read a CSV file that uses either the CSV module or
the pandas
library.
=>The csv Module provides two classes for reading information from CSV file .
1) csv.reader
2) csv.DictReader
--------------------------
1) csv.reader():
--------------------------
=>This Function is used for creating an object of csv.reader class and It helps us
to read the data records from csv file.
=>Syntax:- csvreaderobj=csv.reader(filepointer)
-------------------------------------------------------------------------------------
2) csv.DictReader():
-----------------------------------
=>This Function is used for creating an object of csv.DictReader class and It helps
us to read the data from csv file where it contains dict data(Key,Value).
=>Syntax:- csvdictreaderobj=csv.DictReader(filepointer)
--------------------------------------------------------------------------------------------------------
----------

You might also like