0% found this document useful (0 votes)
11 views162 pages

Python Unit 2

The document is a course outline for a Master of Computer Applications (MCA) program focusing on Programming in Python, covering topics such as functions, exception handling, modules, and file operations. It details the advantages of functions, the difference between functions and methods, and various types of arguments including positional, keyword, default, and variable-length arguments. Additionally, it introduces concepts like recursive functions, lambda functions, decorators, and generators, providing examples and explanations for each topic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views162 pages

Python Unit 2

The document is a course outline for a Master of Computer Applications (MCA) program focusing on Programming in Python, covering topics such as functions, exception handling, modules, and file operations. It details the advantages of functions, the difference between functions and methods, and various types of arguments including positional, keyword, default, and variable-length arguments. Additionally, it introduces concepts like recursive functions, lambda functions, decorators, and generators, providing examples and explanations for each topic.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 162

BipinRupadiya.

com 1
GUJARAT TECHNOLOGICAL UNIVERSITY
MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER: III

Subject Name: Programming in Python


Subject Code : 4639304

BipinRupadiya.com 2
Unit-2
 Functions,
 Exception,
 Modules and
 Files

BipinRupadiya.com 3
Python
Chapter-9
Functions
Text Book:
R Nageswara Rao, Core Python Programming, 2nd Edition, Dreamtech Press

BipinRupadiya.com
Introduction
 It is similar to a program that
consist of a group of statements
that are intendant to perform a
specific task.
 Two types of function:
 User Defined
 Built-In (abs(), len(), sort(), sqrt(),
power())

BipinRupadiya.com
Advantages of Functions:
 Used to process data, make calculations ,
perform task.
 Function as Reusable code
 Function provides Modularity
 Code maintenance is easy because of functions

BipinRupadiya.com
Python Method:
 Method is called by its name, but it is associated to an object (dependent).
 A method is implicitly passed the object on which it is invoked.
 It may or may not return any data.
 A method can operate on the data (instance variables) that is contained by
the corresponding class

Output: I am in method_abc of ABC class

BipinRupadiya.com
Functions:
 Function is block of code that is also called by its name. (independent)
 The function can have different parameters or may not have any at all. If any data
(parameters) are passed, they are passed explicitly.
 It may or may not return any data.
 Function does not deal with Class and its instance concept.

Output: -2 and 9

BipinRupadiya.com
Difference between method and function
 Simply, function and method both look similar as they perform in
almost similar way, but the key difference is the concept of ‘Class and
its Object‘.
 Functions can be called only by its name, as it is defined
independently.
 But methods can’t be called by its name only, we need to invoke the
class by a reference of that class in which it is defined, i.e. method is
defined within a class and hence they are dependent on that class.

BipinRupadiya.com
Defining a Function & Calling a function

Output: -2 and 9 Output: -22 and 15

BipinRupadiya.com
Returning
a result/single value from function
def square(n):
return n*n

r= square(2)
Print(r)

# or print it as before
print(square(2))

BipinRupadiya.com
Returning
multiple value from function
 Python also has the ability to return multiple values from a function
call, something missing from many other languages.
 In this case the return values should be a comma-separated list of
values and Python then constructs a tuple and returns this to the
caller.

def square(x,y):
return x*x, y*y

t = square(2,3)
print(t) # Produces (4,9)

BipinRupadiya.com
Returning a multiple value from function
 An alternate syntax when dealing with multiple return values is to have Python
"unwrap" the tuple into the variables directly by specifying the same number of
variables on the left-hand side of the assignment as there are returned from the
function.

def square(x,y):
return x*x, y*y

xsq, ysq = square(2,3)


print(xsq) # Prints 4
print(ysq) # Prints 9

BipinRupadiya.com
Functions are first class objects
 Functions are first class objects, It means we can use function as
perfect object.
 Since a functions are objects, we can pass functions to another
functions just like an object.
 Also it is possible to return a function from another function.
 Following possibilities are important:
1. Possible to assign function to a variable
2. Possible to define a one function inside the another function.
3. Possible to pass a function as parameter to another function.
4. Possible that a function can return another function.

BipinRupadiya.com
Possible to assign function to a variable:

BipinRupadiya.com
Define
a function inside the another function

BipinRupadiya.com
Pass a function
as parameter to another function.

Here new name of message() function is ‘fun’ (=reference name of message() function)

BipinRupadiya.com
function can return another function

BipinRupadiya.com
Pass by Object Reference
 In function when we pass values, we can think of this two way.
 Pass by value or call by value
 Pass by reference or call by reference

 Pass by value represents that a copy of variable is passed to the


function and modification to that value will not reflect
outside of function.
 Pass by reference represents sending the reference or memory
address of the variable to the function.
 Neither of this two concepts are applicable to Python.

BipinRupadiya.com
Pass by Object Reference
 In a python, values are sent to function by means of Object Reference.
 We know everything is considered as object in python.
 All numbers, strings, datatypes (like tuples, lists, dictionaries)
are object in python.
 In python an object can be imagined as memory block where we
can store some value.
 For example x=10 , here in python 10 is object and x is the
name or tag given to it.

BipinRupadiya.com
Pass by Object Reference
 To know the location of the an object in heap, we can use id()
function that gives an identity number of an object.
 X = 10
 id(x)
 Output= 1154899390
 This number may change computer to computer

BipinRupadiya.com
Exampel-1: Pass by Object Reference
 A python program to pass an integer to a function and modify it.

Here in function x= 15 but it will not be available outside of


function when we modify its value by x=10

BipinRupadiya.com
Exampel-2: Pass by Object Reference
 A program to modify the list to a function .

BipinRupadiya.com
Exampel-3: Pass by Object Reference
 A python program to create a new object inside the function does not
modify outside object.

BipinRupadiya.com
Formal and actual argument
 Formal Arguments
 When you define function , it may have some parameters. These parameters are
useful to receive values from outside of function. They are called ‘Formal Arguments’.
 Actual Arguments
 When we call the function we should pass the data or values to the function. These
values are called ‘Actual Arguments’

Here,
a and b formal arguments

And
x and y are actual arguments

BipinRupadiya.com
Formal and actual argument
 Actual arguments used in a function are of 4 types.
1. Positional arguments
2. Keyword arguments
3. Default arguments
4. Variable length arguments

BipinRupadiya.com
Positional Argument:
 When we call a function with some values, these values get assigned
to the arguments according to their position.
 These are the arguments passed to a function in correct positional
order.

BipinRupadiya.com
Keyword argument:
 When we call a function with some values, these values get assigned
to the arguments according to their position.
 Python allows functions to be called using keyword arguments. When
we call functions in this way, the order (position) of the arguments
can be changed.
 This kind of argument identify the parameter by their name

BipinRupadiya.com
Default Argument:
 Function can have default argument using = operator
 It can assign from right to left only.
 Any number of arguments in a function can have a default value. But
once we have a default argument, all the arguments to its right must
also have default values.
 Default argument is optional during a call. If a value is provided, it
will overwrite the default value.
 Example : def fun(a, b=8, c=90) Here b=8, c=90 is set default.

BipinRupadiya.com
Variable length argument:
In Python, we can pass a variable number of arguments to a
function using special symbols.
There are two special symbols:
 *args (Non Keyword Arguments)
 **kwargs (Keyword Arguments)

BipinRupadiya.com 30
Non Keyword Variable length argument:
 When the programmer does not know how many argument a function may
receive, at that time variable length concept is used.
 we should use an asterisk * before the parameter name to pass variable length
arguments.
 The arguments are passed as a tuple and these passed arguments make tuple
inside the function with same name as the parameter excluding asterisk *.

Output
<class 'tuple'> (1, 2, 3)

BipinRupadiya.com
Keyword Variable length argument:
 Use double asterisk ** before the parameter name to denote this
keyword variable length of argument.
 The arguments are passed as a dictionary and these arguments make
a dictionary inside function with name same as the parameter
excluding double asterisk **.

Output
<class 'dict'> {'a': 11, 'b': 33, 'c': 22}
BipinRupadiya.com
Local Variables
 A local variable is a variable whose scope is limited only to that function where it
is created.

BipinRupadiya.com
Global Variables
 When a variable is declared above a function, it becomes global
variable.

BipinRupadiya.com
The Global Keyword
 Sometimes global and local variable have same name.
 In that case, function by default refer to the local variable and ignores the global
variable.
 So the global variable is not accessible inside the function but outside of it, it is
accessible.

BipinRupadiya.com
The Global Keyword
 if we wants to use global variable inside the function,
 Use the ‘global’ keyword before the variable in the beginning of function body as,
 global a;

BipinRupadiya.com
The Global Keyword

BipinRupadiya.com
Passing a group of Element to a function

 To pass a group of element like numbers or string, we can accept them into a list
and then pass the list to the function .

Example:

BipinRupadiya.com
Passing a group of Element to a function

BipinRupadiya.com
Recursive Function
 A function that calls itself is known as ‘recursive function’.
 Eg:-factorial

BipinRupadiya.com
Recursive Function: Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n
disks. The objective of the puzzle is to move the entire stack to another
rod, obeying the following simple rules:

1) Only one disk can be moved at a time.

2) Each move consists of taking the upper disk from one of the stacks
and placing it on top of another stack i.e. a disk can only be moved if it is
the uppermost disk on a stack.

3) No disk may be placed on top of a smaller disk.

BipinRupadiya.com
Tower of Hanoi

BipinRupadiya.com
Tower of Hanoi Example

OUTPUT:
moving disk from A to C
moving disk from A to B
moving disk from C to B
moving disk from A to C
moving disk from B to A
moving disk from B to C
moving disk from A to C
BipinRupadiya.com
Anonymous/Lambda Function
 What are lambda functions in Python?
 anonymous function is a function that is defined without a name.

 While normal functions are defined using the def keyword


 anonymous functions are defined using the lambda keyword.

 Hence, anonymous functions are also called lambda functions.

BipinRupadiya.com
Anonymous/Lambda Function
 How to use lambda Functions in Python?
 Syntax: lambda arguments: expression

OUTPUT

30

BipinRupadiya.com
Use of Lambda Function
 We use lambda functions when we require a nameless
function for a short period of time.
 we generally use it as an argument to a higher-order
function
 Higher-order function is a function that takes in other
functions as arguments
 Lambda functions are used along with built-in functions like
filter(), map() etc.

BipinRupadiya.com
Using lambda with filter()
 The filter() function takes two arguments: function and a list
 The function is called with all the items in the list and a new list is returned
which contains items for which the function evaluates to True.
 Example:

Sample List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Even List: [2, 4, 6, 8, 10]
Odd List: [1, 3, 5, 7, 9]

BipinRupadiya.com
Using lambda with map()
 The map() function takes two argument: function and a list
 The function is called with all the items in the list and a new list is returned which
contains items returned by that function for each item.
 Example:

OUTPUT:
List: [1, 2, 3, 4]
List: [1, 4, 9, 16]

BipinRupadiya.com
lambda with reduce()
 The reduce() function takes two arguments: function and a list
 The function is called with a lambda function and a list and a new reduced result
is returned.
 This performs a repetitive operation over the pairs of the list.
 This is a part of functools (function tools) module.
 Example:

OUTPUT:
sum : 45

BipinRupadiya.com
Function Decorators
 A decorator is a function that takes a function as its only
parameter and returns a function.
 This is helpful to “wrap” functionality with the same code over
and over again.

BipinRupadiya.com
Function Decorators
 Nested Function Working shown in example:

BipinRupadiya.com
Function Decorators

Output:- Hello Google


BipinRupadiya.com
Generators
 A generator-function is defined like a normal function, but whenever it
needs to generate a value, it does so with the yield keyword rather
than return.
 If the body of a def contains yield, the function automatically becomes
a generator function.

BipinRupadiya.com
Generators
 Generators are used to create iterators, but with a different approach.
 Generators are simple functions which return an iterable set of items,
one at a time, in a special way.
 When an iteration over a set of item starts using the for statement, the
generator is run.
 Once the generator's function code reaches a "yield" statement, the
generator yields its execution back to the for loop, returning a new
value from the set.
 The generator function can generate as many values (possibly infinite)
as it wants, yielding each one in its turn.

BipinRupadiya.com
Generators

Output:-

BipinRupadiya.com
Structured Programming
 The purpose of programming is to solve problems related to various areas.
 Starting problems like adding two numbers to complex problem like
designing engine of air craft we can solve this problem through
programming.
 Solving a complex problem , structured programming is the strategy used
by the programmers.
 In structured programming, the main task is divided into several parts
called Sub tasks and each this task is represented by one or more functions.

BipinRupadiya.com
Structured Programming

BipinRupadiya.com
Structured Programming
 Lets take an example of salary of an employee.(diagram)

BipinRupadiya.com
Creating our own module in python
 A module represents a group of classes, methods , functions and
variables.
 While we are developing software, there may be several classes,
methods and functions.
 We should first group them on depending on their relationship into
various modules and later use these module in the other programs.
 It means, when a module is developed, it can be reused in any
program that needs the module.
 In python , there is several built-in modules like sys, io , time etc.
 Just like this , we can create our own module too, and use them
whenever we need them.

BipinRupadiya.com
Creating our own module in python

BipinRupadiya.com
Creating our own module in python

BipinRupadiya.com
The Special Variable _name_
 When a program is executed in python, there is a special variable internally
created by the name ‘_name_’
 This variable stores information regarding weather the program is executed as
an individual program or as a module.
 When the program is executed directly, the python interpreter stores the value
‘_main_’ into this variable.
 When the program is imported as another program, then python interpreter
stores the module name into this variable.
 So by observing _name_ we can understand how program is executed.

BipinRupadiya.com
The Special Variable _name_
 Lets assume that we have written a program. When this program is run, python
interpreter stores the value ‘__main__’ into the special “__name__”
 Hence we can check if this program run directly as a program or not as:
 If __name__ == ‘__main__’:

BipinRupadiya.com
The Special Variable _name_

BipinRupadiya.com
Python
Chapter-16
Exception

Text Book:
R Nageswara Rao, Core Python Programming, 2nd Edition, Dreamtech Press

BipinRupadiya.com
Introduction
 The errors in software are called bugs.
 And process of removing them is called debugging.

BipinRupadiya.com
Errors in Python
 There are three types of error.
1. Compile time errors
2. Run time errors
3. Logical errors

BipinRupadiya.com
Compile time errors :
 These are syntactical errors found in the code, due to which program
fails to compile.
 For example like …….forgetting a colon in statement like if, while, for ,
def….etc will result in compile time error.
 This will raise Syntax Error.

BipinRupadiya.com
Compile time errors

BipinRupadiya.com
Run Time Error:
 when PVM cant execute byte code, it flags runtime error.
 Runtime errors are not detected by python its detected by PVM at runtime.

BipinRupadiya.com
Solution…
 If correct argument are passes then it work properly

BipinRupadiya.com
Logical error:
 These errors are either because of wrong formula or wrong design of
program itself.
 Logical errors are not detected by python compiler or PVM

BipinRupadiya.com
Exception
 It is a run time error which can be handled by the
programmer.
 That means if a programmer can guess an error
in the program and he can do something to
eliminate the harm caused by that error then it is
called an exception.
 If the programmer can’t do anything in case of
an error, then it is called an error not an
exception.
 All the exception are represented as classes in
python.

BipinRupadiya.com
Exception
 Exceptions which are already available in python are called
as ‘built in’ exception.
 Exceptions which are user defined are developed by
Programmer.
 Base class for built in exception is ‘BaseException’ class
 From BaseException class Subclass Exception has been
derived.
 And from Exception Subclass ‘StandardError’ and
‘Warning’ are derived.
 Here StandardError Must be handled through exception but
warning is fine in program.

BipinRupadiya.com
Exception

BipinRupadiya.com
Exception Handling
 The purpose of handling error is to make the program
Robust.
 To handle the exception, programmer should perform
the following three steps:
1. try
2. except
3. finally

BipinRupadiya.com
try block
1. Observe the statements in program and find out the possibilities
where exception is needed. Such a statements must be write
inside a try block.
The greatness of try block is that even if exception arise inside
the block ,then also program will not be terminated.
 try:

Statements.

BipinRupadiya.com
except block
2. Write ‘except’ block where he should display the exception
detail to the user. This helps to understand the user that there is
an error.
except exceptionname:
Statements

 The statements inside an except block are called handlers.


Since they handle the situations when the exception error occurs.

BipinRupadiya.com
Finally block
3. The programmer should perform clean up action like closing
the files and terminating any other process which are
running.
And the program should write a finally block.
finally:
statements

BipinRupadiya.com
Exception Handling

BipinRupadiya.com
Exception Handling
try:  try contains the statement
statements where there may be one or
except Exception1: more exceptions.
statements
except Exception2:  except block execute when
statements an exception occur in try
except Exception3: block
statements  else block execute when
else: there is no exception will
statements
execute
finally:
statements  finally block will always is
executed.
BipinRupadiya.com
Exception Handling Key Points
 A single try can be followed by several except blocks.
 Multiple except blocks can be used to handle multiple exception
 We cant write except block without try block
 We can write try blocks without any except block
 Else block and Finally block are not compulsory.
 When there is no exception, else block is executed after try block.
 Finally block is always executed.

BipinRupadiya.com
Types of Exceptions
Exception
Base class for all exceptions
StopIteration
Raised when the next() method of an iterator does not point to any object.
SystemExit
Raised by the sys.exit() function.
StandardError
Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
Base class for all errors that occur for numeric calculation.
OverflowError
Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
Raised when a floating point calculation fails.
ZeroDivisonError
Raised when division or modulo by zero takes place for all numeric types.
AssertionError
Raised in case of failure of the Assert statement.
AttributeError
Raised in case of failure of attribute reference or assignment.
EOFError
Raised when there is no input from either the raw_input() or input() function and the end of file is reached.
ImportError
Raised when an import statement fails.
BipinRupadiya.com 83
Types of Exceptions
KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError
Base class for all lookup errors.
IndexError
Raised when an index is not found in a sequence.
KeyError
Raised when the specified key is not found in the dictionary.
NameError
Raised when an identifier is not found in the local or global namespace.
UnboundLocalError
Raised when trying to access a local variable in a function or method but no value has been assigned to it.
EnvironmentError
Base class for all exceptions that occur outside the Python environment.
IOError
Raised when an input/ output operation fails, such as the print statement or the open() function when trying to
open a file that does not exist.
OSError
Raised for operating system-related errors.

BipinRupadiya.com 84
Types of Exceptions
SyntaxError
Raised when there is an error in Python syntax.
IndentationError
Raised when indentation is not specified properly.
SystemError
Raised when the interpreter finds an internal problem, but when this error is encountered the Python
interpreter does not exit.
SystemExit
Raised when Python interpreter is quit by using the sys.exit() function. If not handled in the code, causes
the interpreter to exit.
TypeError
Raised when an operation or function is attempted that is invalid for the specified data type.
ValueError
Raised when the built-in function for a data type has the valid type of arguments, but the arguments have
invalid values specified.
RuntimeError
Raised when a generated error does not fall into any category.
NotImplementedError
Raised when an abstract method that needs to be implemented in an inherited class is not actually
implemented.

BipinRupadiya.com 85
Types of Exceptions

OUTPUT:
Enter Data : 1w
invalid Data

BipinRupadiya.com
Handle IOError
 A python program to handle IOError produced by open() function.

BipinRupadiya.com
Handle Multiple Exception

BipinRupadiya.com
Except Block
 except block is used to catch exception that is raised in try block.
 It is written in various format
1. we can write except block with the exception class name as:
except Exceptionclass:
2. We can catch the exception as an object that contain some information about
the catch exception.
except Exceptionclass as obj;
3. To catch a multiple exception, we can write multiple catch block.
you can also write all the exception as tuple inside parentheses as :
except (Exceptionclass1,Exceptionclass2,….):
4. When we are not bother about which type of exception it is , to catch this type of
exception we need below syntax:
except:

BipinRupadiya.com
Use of finally and try blocks

BipinRupadiya.com
The Assert Statement
 It is useful to ensure that a given condition is True.
 If it is not true, it raise AssertionError.

 Syntax
assert condition, message
 If the condition is false, then AssertionError except is raised along with the
message.
 You can raise AssertionError exception without message too.

BipinRupadiya.com
The Assert Statement

BipinRupadiya.com
The Assert Statement
Example-2

BipinRupadiya.com
User Defined Exception
 Python also allows you to create your own exceptions by deriving classes from the
standard built-in exceptions.
 It is also called custom exception
 To create the user defined exception , user needs to follow below steps:
1. All exceptions are class,
 so programmer needs to create his own exception as class.
 Also he has to make his class as subclass to built-in class Exception.

class MyException(Exception):
def __init__(self,arg):
self.msg = arg

Here this class MyException has a constructor where a variable ‘msg’ is defined.
The ‘msg receives a message passed from outside through ‘arg’.

BipinRupadiya.com
User Defined Exception
2. The programmer can write his codes, when a programmer suspects the
possibilities of exception at that time , he should raise an exception.
raise MyException(‘message’)

3. Try and catch block is shown as below:


try:
code
except MyException as me:
print(me)

BipinRupadiya.com
User Defined Exception

OUTPUT:
A New Exception occurred: 6
BipinRupadiya.com
Logging and Exceptions
 It is a good idea to store all the error message to in some file.
 So a log file is used to store error and exception messages.
 When we store the messages into log file ,we can print or read later
that error.
 This helps to understand programmer , that how many errors are there.
 Python provides logging module to create a log file, that can store all
the error messages.
 There may be different levels of error messages.
 For example, warning errors have less priority than error which crashes
system
 So depending on seriousness, they are classified into 6 levels in logging
module.

BipinRupadiya.com
Logging Error and their Numeric value
Numeric
Level When it’s used
constant
NOTSET 0 Represent that level is not set

DEBUG 10 Detailed information, typically of interest only when diagnosing problems.

INFO 20 Confirmation that things are working as expected.

An indication that something unexpected happened, or indicative of some problem in


WARNING 30
the near future (e.g. ‘disk space low’). The software is still working as expected.
Due to a more serious problem, the software has not been able to perform some
ERROR 40
function.

CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.

BipinRupadiya.com 98
Logging and Exceptions
 To understand the levels of logging messages, see the code below:

BipinRupadiya.com
Logging Exceptions
 Program to store the message released by an exception into the file

BipinRupadiya.com
log.txt

BipinRupadiya.com
Example: Logging syntax error

BipinRupadiya.com
Python
Chapter-17
Modules and Files
Text Book:
R Nageswara Rao, Core Python Programming, 2nd Edition, Dreamtech Press

BipinRupadiya.com
Introduction
 Data is very important in our day to day life.
 Every organization is depend on its data for continuing its business.
 If the data is lost , the organization has to be closed.
 Computers are primarily created for data handling, for storing and
retrieving a data.
 To store a data in computer, we need file.
 a file is nothing but the collection of data that is available to a
computer.
 For example
 we can store employee data like name, number , salary etc in file.

BipinRupadiya.com
Types of files in python
 In python there are two types of files.
1. Text files
2. Binary files
 Text file stores data in the form of characters...
 Example:
 If we store 'Ganesh' then will be stored as 6 characters.
 If we store Employee salary 8900.75 will be store as 7 characters
 Binary file stores entire data in the form of bytes
 Example:
 character is stored as a byte and integer is stored in the form of 8 bytes.
 Binary file can be used to store text, images, audio and video.

BipinRupadiya.com
Open a file
 Syntax:
file handler =open ("file_name", "open_mode", "buffering")
 Example:
f =open("myfile.txt","r")
 Parameter:
 File_name= name of file
 Open_mode= mode of open
 Buffering= temporary block of memory,
 It is an optional integer used to set the size of buffer.
 In binary mode, we can pass 0 to indicate no use of buffer
 In text mode , use 1 for buffering to retrieve the data from file one line
at a time.

BipinRupadiya.com
access modes for open()
 READ

 r: Opens the file in read-only mode. Starts reading from the beginning of the file and is the default mode for the open()
function.

 rb: Opens the file as read-only in binary format and starts reading from the beginning of the file. While binary format can
be used for different purposes, it is usually used when dealing with things like images, videos, etc.

 r+: Opens a file for reading and writing, placing the pointer at the beginning of the file.

 WRITE

 w: Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with
the same name. It will create a new file if one with the same name doesn't exist.

 wb: Opens a write-only file in binary mode.

 w+: Opens a file for writing and reading.

 wb+: Opens a file for writing and reading in binary mode.

 APPEND

 a: Opens a file for appending new information to it. The pointer is placed at the end of the file. A new file is created if one
with the same name doesn't exist.

 ab: Opens a file for appending in binary mode.

 a+: Opens a file for both appending and reading.

 ab+: Opens a file for both appending and reading in binary mode.

BipinRupadiya.com 107
Closing a File
 A file which is opened should be closed using close() method.
 The data file may be corrupted or deleted if you don't close file.
 If you don't close the file, memory utilized by the file is not
freed, leading to the problem like insufficient memory.
 So it is mandatory to close the file.
 Example
f.close()
 Here file object f is closed, means f is deleted/ freed from the
memory.

BipinRupadiya.com
BipinRupadiya.com
The read() Method
 The read() method reads a string from an open file. It is important to
note that Python strings can have binary data. apart from text data.
 Syntax
 fileObject.read([count]);
 Here, passed parameter is the number of bytes to be read from the
opened file.
 This method starts reading from the beginning of the file and if count is
missing, then it tries to read as much as possible, maybe until the end
of file.

BipinRupadiya.com 110
BipinRupadiya.com
Store a group of strings into a text file
we have to use the write() method inside a loop.

BipinRupadiya.com
Read all strings from a text file

BipinRupadiya.com
Append a text file

BipinRupadiya.com
Knowing weather a file exists or not
 The operating system (os) module has a sub module by the name
'path' that contains a method is file()
 This method is used to know , weather the file we are opening is
really exists or not.

BipinRupadiya.com
Knowing weather a file exists or not

BipinRupadiya.com
BipinRupadiya.com
Working with the binary files
 Binary files handle data in the form of bytes.
 They can be used to read or write text, images, audio and video files.
 To open a binary file for reading purpose, we can use 'rb' mode. And
for writing purpose use 'wb' mode
 b is attached to 'r ' to show that is binary file. Same for 'wb'.

BipinRupadiya.com
BipinRupadiya.com
The With statement
 The with statement can be used while opening a file.
 The advantage of with statement is that it will take care of
closing a file which is opened by it.
 So we don't need to close the file explicitly.
 In case of an exception also, 'with' statement will close the
file before the exception is handled.
 Syntax
with open("filename","openmode") as fileobject:

BipinRupadiya.com
BipinRupadiya.com
BipinRupadiya.com
Pickel in python
 So far we have work with simple file, but what happens if we want
to store some structured data in the file?
 For example, we want to store some employee detail like employee
identification (int), name(string), salary(float) in file.
 This data is called structured and got different type.
 To store such a data we need to create class Employee with
the instance variable I'd, name, sal,..

BipinRupadiya.com
Pickel in python
 Then we create an object to this class and store actual data
into that object.
 Later this object should be stored into a binary file in the
form of bytes.
 This is called pickle or serialization.
 So Pickle is the process of converting a class objects into a
byte stream so that it can be stored into a file.----this is called
object serialization.

BipinRupadiya.com
Pickel in python
 Pickling is done using the dump() method of ‘pickle’
module:
pickle.dump(object,file)
 This statement will store the object into the binary file.
 Once the object are stored into a file, we can read from
the file at any time.

BipinRupadiya.com
Pickel in python
 Unpickle is the process whereby a byte stream is converted
back into a class object.
 It means unpickle represents reading the class objects from the
file.
 Unpickling is also called de-serialization.
 Unpickling is done using the load() method of ‘pickle’ module:
object= pickle.load(file)

BipinRupadiya.com
Pickel in python

BipinRupadiya.com
BipinRupadiya.com
BipinRupadiya.com
BipinRupadiya.com
The seek() and the tell() method
 In the binary files data is stored in the binary form,
 so when we conduct the reading or writing operation of
binary file, a file pointer moves inside the file depending
on how many bytes are written or read from the file.

BipinRupadiya.com
tell() method
 To know the position of the file pointer, we can use the tell() method.
 It returns the current position of the file pointer from the beginning of the file.

Syntax:
n= f.tell()

where
f=handler/file object
n=integer which represents byte.

BipinRupadiya.com
seek()
 Now if we want to move a file pointer to another position, we can use the
seek() method
Syntax:
 f.seek(offset, fromwhere)
 offset
0 means beginning of the file
1 means current position of the file pointer
2 means end of the file
 f.seek(10) same as f.seek(10,0) here pointer will go from 0 to 11th
(10+1) byte position form the beginning of the file.
 f.seek(-10,2) here pointer will go from ending of the file to 9th byte(-
10+1). Here 2 represents the ending of the file.

BipinRupadiya.com
Example: seek()
 The String’s characters and their bytes positions in file

 f.seek(3) :
 print(f.read(2)) : ans=zi
 it will read to byte from the current
pointer position which is ‘z’ so ans will be
‘zi’
 print(f.tell()) : ans=5
 print(f.seek(4,1)) :
 ans= ‘y’ it will move pointer from current
position, so it will point to ‘y’ character.
 print(f.read(1)): ans= y
 print(f.tell()) : ans= 10

BipinRupadiya.com
Random Accessing of Binary files
 Data in binary files is stored in the form of continues bytes.
 Lets take binary file having 1000 bytes of data.
 If we want to access the last 10 bytes of data,
 it is not needed to search the file bytes by byte from the beginning.
 It is possible to go to the 991st byte using seek() method only.
f.seek(900)
 Then read the last 10 bytes using read() method,
read(10)
 In this way, we can directly go to any byte in the binary file is called random
accessing.

BipinRupadiya.com
Strings in Binary files
 A problem with binary file is that , they accept data in the form of bytes or
binary format.
 For example, if we store a string into a binary file, as we shown in the following
statement, we will end up in the error.

BipinRupadiya.com
Strings in Binary files
 Converting a string literal into the binary format can be done by prefixing
the characteristic ‘b’ before the string,
as: b’Hello’
as: b’Dear’
 On the other hand, to convert a string variable into binary format, we
have to use encode() method as: str.encode()
 similar, to read a string from binary format to readable text, we have to
use decode() method as: str.decode()

BipinRupadiya.com
Add Strings in Binary files

BipinRupadiya.com
Read Strings in Binary files

BipinRupadiya.com
Random Accessing of Binary files using mmap
 mmap-memory mapped file
 mmap is a module in python
 It is useful to map or link to a binary file and manipulate the data of the file as
well just like string

 mm=mmap.mmap (f.fileno(),0)
 This will map the currently opened file (f) with the object ‘mm’
 f.fileno() indicates that fileno() is a handle to the file object ‘f’.
 This ‘f’ represents the actual binary file that is being mapped.
 The second argument is 0 which represents the total size of file should be considered for
mapping.

 So entire file represented by ‘f’ is mapped in memory to object ‘mm’.


 So now mm will now onwards behave like file

BipinRupadiya.com
Random Accessing of Binary files using mmap
 print(mm.read()) #display entire file
 print(mm.readline()) #display the first line of file
 print(mm[5:]) #display from 5th byte till the end.
 print(mm[5:10]) #display 5th byte to 9th byte.
 mm[5:10] = str.encode() #store from 5th to 9th bytes.
 n=mm.find(name) #return the position of name in file
 mm.seek(10,0) #position the file pointer to 10th byte from

BipinRupadiya.com
BipinRupadiya.com
mmap example
Python code to do random access
In binary file using mmap()
We will do
Display
Search and
Update

BipinRupadiya.com
BipinRupadiya.com
What is a zip file?
 ZIP is an archive file format that supports lossless data compression.
 By lossless compression, we mean that the compression algorithm
allows the original data to be perfectly reconstructed from the
compressed data.
 So, a ZIP file is a single file containing one or more compressed files,
offering an ideal way to make large files smaller and keep related files
together.
Why do we need zip files?
 To reduce storage requirements.
 To improve transfer speed over standard connections.

BipinRupadiya.com 145
Zipping and unzipping files
 In zipping the file content, following two things could happen:
 The file contents are compressed and hence the size will be reduce.
 The format of data will be changed making it unreadable.
 While zipping a file content , a zipping algorithm(logic) is used in such a way
that the algorithm first find out which bit pattern is most often repeated
in the original file and replaces that bit pattern with a 0.
 Then the algorithm searches for next bit pattern which is most often
repeated in input file. In this place 1 is substituted.
 Third repeated bit pattern will be replaced by 10, the fourth by 11 , fifth by
100 and so on.
 In this way, the original bit patterns are replaced by lesser numbers of bits.
 The file with lesser number of bits is called ‘zipped file’ or ‘compressed file’.

BipinRupadiya.com
Zipping and unzipping files
 To get back the original data from the zipped file, we can follow a
reverse algorithm, which substitute the original bit pattern wherever
particular bits are found.
 Fig.17.4

1010 1010 0
1111 0010 zipping 1
0101 1110 10
1111 0001 unzipping 11

Original file compressed file

BipinRupadiya.com
Zipping and unzipping files
 In a python, zipfile contains ZipFile class that help us to zip or unzip a file
content.
 For example to zip the file we should first pass the zip file name in write
mode with an attribute ZIP_DEFLATED to the zipfile calss object as:
f = zipfile(‘test.zip’, ‘w’, ZIP_DEFLATED)
Here ‘f’ is the zipfile class object to which test.zip file name is passed.
 Next step is to add the filenames that are to be zipped, using write()
method as:
f.write(‘file1.txt’)
f.write(‘file2.txt’)

BipinRupadiya.com
Example: creating zip file

BipinRupadiya.com
Example: unzipping file

BipinRupadiya.com
Working with the Directories
 The os module represents operating system dependent
functionality.
 The module is useful to perform some operation on directories.

BipinRupadiya.com
makdir()

BipinRupadiya.com
makedirs()

BipinRupadiya.com
chdir()

BipinRupadiya.com
rmdir()

BipinRupadiya.com
removedirs()

BipinRupadiya.com
rename()

BipinRupadiya.com
walk()
walk() generates the file names in a directory tree by walking the tree either top-
down or bottom-up.

 Syntax
 os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
 Parameters
 top − Each directory rooted at directory, yields 3-tuples, i.e., (dirpath, dirnames,
filenames)
 topdown − If optional argument topdown is True or not specified, directories are
scanned from top-down. If topdown is set to False, directories are scanned from
bottom-up.
 onerror − This can show error to continue with the walk, or raise the exception to abort
the walk.
 followlinks − This visits directories pointed to by symlinks, if set to true.

BipinRupadiya.com
Example: walk()

BipinRupadiya.com
Running other programs from python
program
 The ‘os’ module has the system() method that is useful to
run an executable program from our python program.
 This is similar to system() function of C language.
 Note: * wild card character means ‘all’

BipinRupadiya.com
Example

BipinRupadiya.com
Bipin S. Rupadiya
(MCA, PGDCA, BCA)
Assistant Professor,
JVIMS-MCA (537), Jamnagar
www.BipinRupadiya.com

BipinRupadiya.com 162

You might also like