Using Python Libraries: Collection of Modules
Using Python Libraries: Collection of Modules
COLLECTION OF MODULES
Introduction
As our program become larger and more complex the
need to organize our code becomes greater. We have
already learnt in Function chapter that large and
complex program should be divided into functions that
perform a specific task. As we write more and more
functions in a program, we should consider organizing of
functions by storing them in modules
A module is simply a file that contains Python code.
When we break a program into modules, each modules
should contain functions that perform related tasks.
Commonly used modules that contains source code for
generic needs are called Libraries.
Introduction
When we speak about working with libraries in
Python, we are, in fact, working with modules that
are created inside Library or Packages. Thus a
Python program comprises three main components:
🞑 Library or Package
🞑 Module
🞑 Function/Sub-routine
Relationship between Module, Package
and Library in Python
A Module is a file containing Python definitions
(docstrings) , functions, variables, classes and
statements
Python package is simply a directory of Python
module(s)
Library is a collection of various packages.
Conceptually there is no difference between
package and Python library. In Python a library is
used to loosely describe a collection of core or main
modules
Commonly used Python libraries
STANDARD LIBRARY
math module Provides mathematical functions
cmath module Provides function for complex numbers
random module For generating random numbers
Statistics module Functions for statistical operation
Urllib Provides URL handling functions so that you can access websites from
within your program.
NumPy library This library provides some advance math functionalities along with
tools to create and manipulate numeric arrays
SciPy library Another useful library that offers algorithmic and mathematical tools
for scientific calculation
Tkinter library Provides traditional user interface toolkit and helps you to create
user friendly GUI interface for different types of applications.
Matplotlib library Provides functions and tools to produce quality output in variety of
formats such as plot, charts, graph etc,
What is module?
Act of partitioning a program into individual
components(modules) is called modularity. A module
is a separate unit in itself.
🞑 It reduces its complexity to some degree
🞑 It creates numbers of well-defined, documented
boundaries within program.
🞑 Its contents can be reused in other program, without
having to rewrite or recreate them.
Structure of Python module
A python module is simply a normal python file(.py)
and contains functions, constants and other elements.
Python module may contains following objects:
docstring Triple quoted comments. Useful for documentation
purpose
Variables and For storing values
constants
Classes To create blueprint of any object
Objects Object is an instance of class. It represent class in real world
Statements Instruction
Functions Group of statements
Composition/Structure of python module
MODULES
VARIABLES OTHER
PYTHON
MODULES
FUNCTIONS
VARIABLES
IMPORT
CLASSES
MEMBERS OTHER
PYTHON
METHODS MODULES
Importing Python modules
To import entire module
import
<module name>
Example: import math
IN THE C:\USERS\VIN
A new Folder “mypackage” is
created.
Note: you can create folder in
any desired location
Creating Package
Step 2: Create modules (.py) and save it in
“mypackage” folder
area.py
Creating Package
Step 2: importing package and modules in python
program
path of
Another example of creating and using
package and module and init .py
Now our entire content structure will be as:
Run the choco.py file and you will get the output.
TIP : to use package from any location
At this time, the package “mypackages” will be accessible
from its location only i.e. the file which wants to import this
package must be in same folder/drive where “mypackages”
is.
To enable “mypackages” to be used from any location, Copy
this mypackages to Python‟s site-packages folder inside Lib
folder of Python‟s installation folder. (Try with copying to Lib
folder also)
Path of site-packages is :
C:\Users\vin\AppData\Local\Programs\Python\Python
36-32\Lib\site-packages
After this you can import this package “mypackages” in any
python file.
Using Python‟s Built-in Function
Python‟s standard library is very extensive that
offers many built-in functions that we can use
without having to import any library.
Using Python‟s Built-in functions
Function_name()
Mathematical and String functions
oct(int) : return octal string for given number by prefixing “0o”
hex(int) : return octal string for given number by prefixing “0x”
Mathematical and String functions
int(number) : function convert the fractional number
to integer
int(string) : convert the given string to integer
round(number,[nDIGIT]) : return number rounded to
nDIGIT after decimal points. If nDIGIT is not given, it
returns nearest integer to its input.
Examples: (next slide)
Mathematical and String functions
Other String function
We have already used many string function in class
XI, here are few new functions
<string>.join() : if the string based iterator is a string then
the <string> is inserted after every character of the string.
If the string based iterator is a list or tuple of strings then, the
given string/character is joined after each member of the list of
tuple. BUT the tuple or list must have all members as string
otherwise Python will raise an error
Examples (next slide)
Other String function
Other String function
We have already used many string function in class
XI, here are few new functions
<string>.split() : allow to divide string in multiple parts
and store it as a LIST. If you do not provide delimeter then
by default string will be split using space otherwise using
given character.
myfile.csv
OUTPUT
Example : Reading from CSV File
myfile.csv
Example : Reading from CSV File
myfile.csv
Third line: to create reader object, to perform read operation on csv file, the first
parameter is the name of csv file, and second parameter is delimiter i.e. on what
basis value of different field to read, by default it is comma(,) so this is optional if
not given it will be by default comma, however if any other character is used in file
then we must specify this. myreader will become csv reader object to read csv file.
Example : Reading from CSV File
myfile.csv
Fourth line : this is formatted string to specify width of each column, so that output
appears properly aligned in their width, here %10s means 10 space for EMPNO,
and so on. This is helpful in printing output in formatted way.
Sixth line :- this line is used to read each row from file one by one and store in row
variable. i.e. all the comma separated values will be stored in row in different index
Example : Reading from CSV File
myfile.csv
Seventh Line :- this line is simply printing all the values in row variable by
specifying index i.e. index 0 will be for (according to first row in file) 1, 1 for „Amit‟,
2 for 6000. here also we used same width as for heading so that both heading and
data are aligned properly
Example : Reading from CSV File
OUTPUT
myfile.csv
OUTPUT
Example : Sum of Salary and counting employee
getting more than 7000
myfile.csv
Example : Sum of Salary and counting employee
getting more than 7000
myfile.csv
OUTPUT
Writing date in CSV file
import csv module
Use open() to open CSV file by specifying mode
“w” or “a”, it will return file object.
“w” will overwrite previous content
“a” will add content to the end of previous content.
Pass the file object to writer object with delimiter.
Then use writerow() to send data in CSV file
Example : Writing data to CSV file
myfile.csv
Example : Writing data to CSV file
Fourth line: we have take a variable ans=„y‟ so that loop will iterate as long
as ans value is „y‟
Fifth line: we have create a while loop using ans i.e. as long as ans is „y‟ loop
will iterate.
Next 3 lines : we have taken input for eno, name and salary
Example : Writing data to CSV file
Ninth line : in this line we are writing data to csv file using writerow() of
mywriter in the form of list. This function takes any iterable object to write
like list, tuples, etc. So we have passed all the input in the form of list.
Another function is writerows() which is used when we want to write multiple
rows.
Next two lines are simple printing message and taking input in ans to contiue
or not.
Example : Writing data to CSV file
myfile.csv
BEFORE EXECUTION
myfile.csv
OUTPUT AFTER EXECUTION
Program to create CSV file and store empno,name,salary and
search any empno and display name, salary and if not found
appropriate message.
OUTPUT
Enter Employee Number 1 Enter Employee Number to search :2
Enter Employee Name Amit ============================
Enter Employee Salary :90000 NAME : Sunil
## Data Saved... ## SALARY : 80000
Add More ?y Search More ? (Y)y
Enter Employee Number 2 Enter Employee Number to search :3
Enter Employee Name Sunil ============================
Enter Employee Salary :80000 NAME : Satya
## Data Saved... ## SALARY : 75000
Add More ?y Search More ? (Y)y
Enter Employee Number 3 Enter Employee Number to search :4
Enter Employee Name Satya ==========================
Enter Employee Salary :75000 EMPNO NOT FOUND
## Data Saved... ## ==========================
Add More ?n Search More ? (Y)n
BINARY FILE HANDLING
Handling the file in the way computer understands
Writing String to Binary file
• To store string in binary file, we must convert it to binary
format either by prefixing the string with ‘b’ or using the
encode() function.
For e.g.
We can use ‘a’ in
place of ‘w’ for
append
Reading Binary file in String
We can
observe,
without
decoding it
will prefix
text with ‘b’
Program to create Binary file and store few records in it
Accessing record randomly from Binary File
Program to search for name in binary file
and display record number
Program to search for name in binary file
and display record number
Program to update name in Binary File
Program to update name in Binary File
Program to delete name from binary file
Program to delete name from binary file
Pickling – Storing employee details in binary file
Un-Pickling – Reading and Display Record
Un-Pickling – Display Record (Formatted Output)
Searching in Binary File
Finding Number of Record in Binary File
Updating Employee Record
VINOD KUMAR VERMA,PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
1. OPENING FILE
We should first open the file for read or write by
specifying the name of file and mode.
2. PERFORMING READ/WRITE
Once the file is opened now we can either read or
write for which file is opened using various functions
available
3. CLOSING FILE
After performing operation we must close the file
and release the file for other application to use it,
Opening File
myfile = open(“story.txt”)
here disk file “story.txt” is loaded in
memory and its reference is linked to “myfile”
object, now python program will access
“story.txt” through “myfile” object.
here “story.txt” is present in the same
folder where .py file is stored otherwise if disk
file to work is in another folder we have to give
full path.
Opening File
myfile = open(“article.txt”,”r”)
here “r” is for read (although it is by default, other
options are “w” for write, “a” for append)
myfile = open(“d:\\mydata\\poem.txt”,”r”)
here we are accessing “poem.txt” file stored in
separate location i.e. d:\mydata folder.
at the time of giving path of file we must use double
backslash(\\) in place of single backslash because in python
single slash is used for escape character and it may cause
problem like if the folder name is “nitin” and we provide path
as d:\nitin\poem.txt then in \nitin “\n” will become escape
character for new line, SO ALWAYS USE DOUBLE
BACKSLASH IN PATH
Opening File
myfile = open(“d:\\mydata\\poem.txt”,”r”)
another solution of double backslash is
using “r” before the path making the string as
raw string i.e. no special meaning attached to
any character as:
myfile = open(r“d:\mydata\poem.txt”,”r”)
:
File Handle
myfile = open(r“d:\mydata\poem.txt”,”r”)
myfile.close()
SAMPLE FILE
Questions…
Writing onto files
After read operation, let us take an example
of how to write data in disk files. Python
provides functions:
write ()
writelines()
The above functions are called by the file
handle to write desired content.
Name Syntax Description
write() Filehandle.write(str1) Writes string str1 to file referenced
by filehandle
Writelines() Filehandle.writelines(L) Writes all string in List L as lines to
file referenced by filehandle.
Example-1: write() using “w” mode
Example-1: write() using “w” mode
Now we can observe that while writing data to file using “w” mode the previous
content of existing file will be overwritten and new content will be saved.
If we want to add new data without overwriting the previous content then we
should write using “a” mode i.e. append mode.
Example-2: write() using “a” mode
New content is
added after previous
content
Example-3: using writelines()
Example-4: Writing String as a record
to file
Example-4: To copy the content of one
file to another file
flush() function
ch = myfile.read(1)
ch will store first character i.e. first character is consumed, and file pointer will
move to next character
File Modes and Opening position
of file pointer
FILE MODE OPENING POSITION
r, r+, rb, rb+, r+b Beginning of file
w, w+, wb, wb+, w+b Beginning of file (overwrites the file if
file already exists
a, ab, a+, ab+, a+b At the end of file if file exists otherwise
creates a new file
Standard INPUT, OUTPUT and ERROR STREAM
&
DRIVE/FOLDER/FILE HIERARCHY
C:\
DRIV E
SALES IT HR PROD
FOLDER FOLDER FOLDER R FOLDER
SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER
.\2019\SHEET.XLS
Relative addressing
Current working
directory
C:\
DRIVE
SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER