These functions are created by the programmer as needed to perform specific tasks within their program. They allow the programmer to encapsulate a set of statements into a single block that can be called whenever necessary. User-defined functions help in modularizing the code, making it easier to read, understand, and maintain.These functions are part of the programming language's standard library and are available for use without requiring the programmer to define them. They serve various purposes and are commonly used for tasks like mathematical operations, string manipulation, sorting, and more.Remember, functions aid in organizing code, improving readability, and promoting code reusability, which are crucial aspects of efficient programming and software development.
5. 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())
6. 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
7. 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
8. 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
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.
12. 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)
13. 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
14. 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.
17. BipinRupadiya.com
Pass a function
as parameter to another function.
Here new name of message() function is ‘fun’ (=reference name of message() function)
19. 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.
20. 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.
21. 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
22. 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
24. BipinRupadiya.com
Exampel-3: Pass by Object Reference
A python program to create a new object inside the function does not
modify outside object.
25. 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
26. 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
27. 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.
28. 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
29. 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.
30. 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)
30
31. BipinRupadiya.com
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)
32. 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}
35. 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.
36. 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;
38. 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:
41. 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.
43. 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
44. 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.
46. 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.
47. 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]
48. 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]
49. 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
50. 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.
53. 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.
54. 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.
56. 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.
59. 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.
62. 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.
63. 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__’:
68. 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.
70. 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.
72. 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
73. 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.
74. 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.
76. 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
77. 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.
78. 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.
79. 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
81. BipinRupadiya.com
Exception Handling
try contains the statement
where there may be one or
more exceptions.
except block execute when
an exception occur in try
block
else block execute when
there is no exception will
execute
finally block will always is
executed.
try:
statements
except Exception1:
statements
except Exception2:
statements
except Exception3:
statements
else:
statements
finally:
statements
82. 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.
83. 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.
83
84. BipinRupadiya.com
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.
84
Types of Exceptions
85. BipinRupadiya.com
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.
85
Types of Exceptions
89. 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:
91. 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.
94. 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’.
95. 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)
97. 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.
98. BipinRupadiya.com
Logging Error and their Numeric value
Level
Numeric
constant
When it’s used
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.
WARNING 30
An indication that something unexpected happened, or indicative of some problem in
the near future (e.g. ‘disk space low’). The software is still working as expected.
ERROR 40
Due to a more serious problem, the software has not been able to perform some
function.
CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.
98
104. 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.
105. 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.
106. 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.
107. 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.
107
108. BipinRupadiya.com
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.
110. 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.
110
115. 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.
118. 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'.
120. 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:
123. 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,..
124. 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.
125. 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.
126. 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)
131. 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.
132. 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.
133. 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.
134. 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
135. 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.
136. 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.
137. 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()
140. 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
141. 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
145. 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.
145
146. BipinRupadiya.com
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’.
147. 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
1111 0010
0101 1110
1111 0001
0
1
10
11
zipping
unzipping
Original file compressed file
148. 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’)
151. BipinRupadiya.com
Working with the Directories
The os module represents operating system dependent
functionality.
The module is useful to perform some operation on directories.
158. 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.
160. 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’