Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views142 pages

Using Python Libraries: Collection of Modules

The document provides an overview of Python libraries, modules, and packages, emphasizing the importance of organizing code into modules for better manageability in complex programs. It explains the structure of Python modules, how to import them, and the creation of custom modules and packages, including the use of __init__.py files. Additionally, it covers commonly used libraries and built-in functions, as well as the use of the urllib and webbrowser modules for web-related tasks.

Uploaded by

prajin.gravity
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)
5 views142 pages

Using Python Libraries: Collection of Modules

The document provides an overview of Python libraries, modules, and packages, emphasizing the importance of organizing code into modules for better manageability in complex programs. It explains the structure of Python modules, how to import them, and the creation of custom modules and packages, including the use of __init__.py files. Additionally, it covers commonly used libraries and built-in functions, as well as the use of the urllib and webbrowser modules for web-related tasks.

Uploaded by

prajin.gravity
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/ 142

USING PYTHON LIBRARIES

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

 To import specific function/object from module:


 from <module_name> import <function_name>
 Example: from math import sqrt

 import * : can be used to import all names from


module into current calling module
Accessing function/constant of imported module

 To use function/constant/variable of imported


module we have to specify module name and
function name separated by dot(.). This format is
known as dot notation.
 <module_name>.<function_name>
 Example: print(math.sqrt(25))
Example : import module_name
Example: from module import function

 By this method only particular method will be


added to our current program. We need not to
qualify name of method with name of module. Or
example:
Here function
sqrt() is
directly written

This line will not


be executed and
gives an error
Example: from module import *
 It is similar to importing the entire package as
“import package” but by this method qualifying
each function with module name is not required.

We can also import multiple elements of module as :


from math import sqrt, log10
Creating our own Module
 Create new python file(.py) and type the following
code as: Execute the following code to import
and use your own module

Save this file are “area.py”


help() function
 Is used to get detailed information about any
module like : name of module, functions inside
module, variables inside module and name of file
etc.
Namespace
 Is a space that holds a bunch of names. Consider an
example:
🞑 Ina CCA competition of vidyalaya, there are students from
different classes having similar names, say there are three
POOJA GUPTA, one from class X, one from XI and one from
XII
🞑 As long as they are in their class there is no confusion, since
in X there is only one POOJA GUPTA, and same with XI and
XII
🞑 But problem arises when the students from X, XI, XII are
sitting together, now calling just POOJA GUPTA would
create confusion-which class‟s POOJA GUPTA. So one need
to qualify the name as class X‟s POOJA GUPTA, or XI‟s or
XII‟s and so on.
Namespace
 From the previous example, we can say that class X has its
own namespace where there no two names as POOJA
GUPTA; same holds for XI and XII 
 In Python terms, namespace can be thought of as a named
environment holding logical group of related objects. 
 For every python module(.py), Python creates a namespace
having its name similar to that of module‟s name. That is,
namespace of module AREA is also AREA.
 When 2 namespace comes together, to resolve any kind
of object name dispute, Python asks you to qualify the
name of object as <modulename>.<objectname>
Processing of import <module>
 The code of import module is interpreted and
executed
 Defined functions and variables in the module are
now available to program in new namespace
created by the name of module
 For example, if the imported module is area, now
you want to call the function area_circle(), it
would be called as area.area_circle()
Processing of from module import object

 When we issue from module import object command:


 The code of imported module is interpreted and executed
 Only the asked function and variables from module are now
available in the current namespace i.e. no new namespace is
created that’s why we can call object of imported module without
qualifying the module name
 For example:
from math import sqrt
print(sqrt(25))
 However if the same function name is available in current
namespace then local function will hide the imported module’s
function
 Same will be apply for from math import * method
Creating Package
 Step 1
 Create a new folder which you want to act as package. The
name of folder will be the name of your package

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

Save this file by


“anyname.py” outside
the package folder

RUN THE PROGRAM


Creating Alias of Package/module
 Alias is the another name for imported package/module. It
can be used to shorten the package/module name 

Save this file by


“anyname.py” outside
the package folder

RUN THE PROGRAM


init .py file
 init .py (double underscore is prefixed and suffixed) : This
file is required to make Python treat directories containing the
file as packages.
 init .py can be just empty file, but it can also execute
initialization code for the package.
 Note: Python 2 requires init .py to be inside a folder in
order for the folder to be considered a package and made
importable but in Python 3.3 and above, it support implicit
namespace packages, all folders are packages regardless
of the presence of a init .py file
 So from Python 3.3 it is optional to create init .py file
Example - creating and using package
and module and init .py
 Create a folder to act as a package
 For. e.g. In C: (C Drive) a folder “mypackages” is
created
 Create init .py file (do not write any thing in it) in
this folder “mypackages”
 Now create another folder “package1” inside
“mypackages”
 Create init .py file inside “package1” also
 Create a module(.py) for e.g. “mymodule.py” file in
“package1” to have some functions in it.
Another example of creating and using
package and module and init .py
 mymodule.py
Another example of creating and using
package and module and init .py
 Now our entire contents will be like this:
Here,
mypackages
and
package1 are
folders

 Now in C: (C Drive), create a file for e.g. “choco.py”


in which we will import module “mymodule”
Another example of creating and using
package and module and init .py
 To import the packages, we can either use Absolute
addressing or Relative Addressing. (already discussed in
data file handling chapter)
 Absolute means following the complete address whereas
Relative means with relation to current folder by using Single
dot(.)

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.

 <str>.replace() : allows you to replace any part of string


with another string.

 Example (NEXT SLIDE)


Example (split() and replace())
Using URLLIB and WEBBROWSER modules

 Python provides urllib module to send http request


and receive the result from within your program. To
use urllib we have to first import urllib module.
 urllib module is a collection of sub-module like
request, error, parse etc. following functions of
urllib we can use: (next slide)
Functions of URLLIB
FUNCTION NAME PURPOSE
urllib.request.urlopen(<url>) Opens a website or network object
denoted by URL for reading and return
file like object using which other functions
are often used
urlopen_object.read() Return HTML or the source code of given
url
urlopen_object..getcode() Returns HTTP status code where 200
means „all okay‟ 404 means url not found
etc. 301, 302 means some kind of
redirections happened
urlopen_object.headers Stores metadata about the open URL

urlopen_object.info() Returns same information as by headers

urlopen_object.geturl() Return URL string


Example:
WEBBROWSER MODULE
 Provides functionality to open a website in a window or tab or
web browser on your computer, from within your program. 
 To use webbrowser module we must import the module as:
🞑import webbrowser
COMMA SEPARATED VALUE
CSV FILE
 CSV is a simple file format used to store tabular data, such as
a spreadsheet or database.
 Files in the CSV format can be imported to and exported from
programs that store data in tables, such as Microsoft Excel or
OpenOffice Calc.
 CSV stands for "comma-separated values“.
 A comma-separated values file is a delimited text file that uses
a comma to separate values. 
 Each line of the file is a data record. Each record consists of
one or more fields, separated by commas. The use of the
comma as a field separator is the source of the name for this
file format
CSV file handling in Python
 To perform read and write operation with CSV file,
we must import csv module. 

 open() function is used to open file, and return file


object.
Reading from CSV file
 import csv module
 Use open() to open csv file, it will return file object.
 Pass this file object to reader object.
 Perform operation you want
Example : Reading from CSV File

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

Here you can see the output is


properly aligned in their
assigned width
How to create CSV file
 Method 1 (From MS-Excel):
🞑 Open Excel, delete all the sheet except sheet 1
🞑 Type all the data, in separate cells

🞑 Save it as csv file in your desired location.


🞑 If any warning comes, click on „YES‟
🞑 When you close the excel, choose „NO‟

🞑 Now file is created at your desired location, go and double


click or open with notepad to check the content
How to create CSV file
 Method 2 (From Notepad):
🞑 Open Notepad
🞑 Type record by separating each column value by comma(,)

🞑 Every record in separate line

🞑 Save it by giving extension .csv (PUT THE NAME IN DOUBLE


QUOTES TO ENSURE .TXT WILL NOT BE APPENDED WITH
FILE NAME FOR E.G. if you want it to save with name emp
then give name as “emp.csv” in double quotes
🞑 File is created close it and double click to open and check
Example : Counting number of records

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

First line : importing csv module to perform operation on csv file.


Second line: to open file for writing in append mode using “with” block,
already discussed with read program.
Third line: to create csv writer object to write in csv file, first parameter is the
name of file object, second one is optional parameter i.e. delimiter. Here
mywriter will be the writer object to write in csv file
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

Updating Employee Record


Deleting Employee Record
Deleting Employee Record
FILE HANDLING
INTRODUCTION
DATA FILES
OPENING AND CLOSING FILES
READING AND WRITING FILES
STANDARD INPUT, OUTPUT AND ERROR STREAMS
Introduction

 FILE HANDLING is a mechanism by which we


can read data of disk files in python program or
write back data from python program to disk
files.
 So far in our python program the standard input
in coming from keyboard an output is going to
monitor i.e. no where data is stored permanent
and entered data is present as long as program is
running BUT file handling allows us to store data
entered through python program permanently in
disk file and later on we can read back the data
DATA FILES

 It contains data pertaining to a specific


application, for later use. The data files can be
stored in two ways –
 Text File
 Binary File
Text File

 Text file stores information in ASCII OR


UNICODE character. In text file everything will
be stored as a character for example if data is
“computer” then it will take 8 bytes and if the
data is floating value like 11237.9876 it will take
10 bytes.
 In text file each like is terminated by special
character called EOL. In text file some
translation takes place when this EOL character
is read or written. In python EOL is ‘\n’ or ‘\r’ or
combination of both
Binary files

 It stores the information in the same format


as in the memory i.e. data is stored according
to its data type so no translation occurs.
 In binary file there is no delimiter for a new
line
 Binary files are faster and easier for a
program to read and write than text files.
 Data in binary files cannot be directly read, it
can be read only through python program for
the same.
Steps in Data File Handling

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

 File can be opened for either – read, write,


append.
SYNTAX:
file_object = open(filename)
Or
file_object = open(filename,mode)

** default mode is “read”


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”)

In the above example “myfile” is the file object


or file handle or file pointer holding the
reference of disk file. In python we will access
and manipulate the disk file through this file
handle only.
File Access Mode
Text Binary File Description Notes
File Mode
Mode
‘r’ ‘rb’ Read only File must exists, otherwise Python raises
I/O errors
‘w’ ‘wb’ Write only If file not exists, file is created
If file exists, python will truncate
existing data and overwrite the file.
‘a’ ‘ab’ Append File is in write mode only, new data will
be added to the end of existing data i.e.
no overwriting. If file not exists it is
created
‘r+’ ‘r+b’ or ‘rb+’ Read and write File must exists otherwise error is raised
Both reading and writing can take place
w+ ‘w+b’ or ‘wb+’ Write and read File is created if not exists, if exists data
will be truncated, both read and write
allowed
‘a+’ ‘a+b’ or ‘ab+’ Write and read Same as above but previous content will
VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &
SACHIN BHARDWAJ, PGT(CS) , KV NO.1 TEZPUR
be retained and both read and write.
Closing file

 As reference of disk file is stored in file handle


so to close we must call the close() function
through the file handle and release the file.

myfile.close()

Note: open function is built-in function used


standalone while close() must be called through file
handle
Reading from File

 To read from file python provide many functions


like :
 Filehandle.read([n]) : reads and return n bytes,
if n is not specified it reads entire file.
 Filehandle.readline([n]) : reads a line of input.
If n is specified reads at most n bytes. Read bytes
in the form of string ending with line character or
blank string if no more bytes are left for reading.
 Filehandle.readlines(): reads all lines and
returns them in a list
Example-1: read()
SAMPLE FILE
Example-2: read()
SAMPLE FILE
Example-3: readline()
SAMPLE FILE
Example-3: readline()
SAMPLE FILE

HAVE YOU NOTICED THE DIFFERENCE IN OUTPUT FROM PREVIOUS OUPUT?


Example-4: reading line by line
SAMPLE FILE
Example-5: reading line U s i n g l o o p
SAMPLE FILE
Example-6: Calculating size of file with and without EOL
and blank lines
SAMPLE FILE
Example-7: readlines
SAMPLE FILE
Example-8 & 9: counting size
of file

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

Lets run the


same program
again
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

 When we write any data to file, python hold


everything in buffer (temporary memory) and
pushes it onto actual file later. If you want to
force Python to write the content of buffer
onto storage, you can use flush() function.
 Python automatically flushes the files when
closing them i.e. it will be implicitly called by
the close(), BUT if you want to flush before
closing any file you can use flush()
Example: working of flush() Nothing is in
the file
temp.txt
Without flush()

When you run the above code, program will


stopped at “Press any key”, for time being
don’t press any key and go to folder where
file “temp.txt” is created an open it to see
what is in the file till now
NOW PRESS ANY KEY….

Now content is stored,


because of close() function
contents are flushed and
pushed in file
Example: working of flush() All contents
before flush()
With flush() are present
in file

When you run the above code, program will


stopped at “Press any key”, for time being
don’t press any key and go to folder where
file “temp.txt” is created an open it to see
what is in the file till now
NOW PRESS ANY KEY….

Rest of the content is


written because of close(),
contents are flushed and
pushed in file.
Removing whitespaces after reading
from file
 read() and readline() reads data from file and
return it in the form of string and readlines()
returns data in the form of list.
 All these read function also read leading and
trailing whitespaces, new line characters. If you
want to remove these characters you can use
functions
 strip() : removes the given character from both ends.
 lstrip(): removes given character from left end
 rstrip(): removes given character from right end
Example: strip(),lstrip(),
rstrip()
File Pointer

 Every file maintains a file pointer which tells the


current position in the file where reading and
writing operation will take.
 When we perform any read/write operation two
things happens:
 The operation at the current position of file pointer
 File pointer advances by the specified number of
bytes.
Example
myfile = open(“ipl.txt”,”r”)

File pointer will be by default at first position i.e. first character

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

 Standard Input : Keyboard


 Standard Output : Monitor
 Standard error : Monitor

 Standard Input devices(stdin) reads from


keyboard
 Standard output devices(stdout) display output
on monitor
 Standard error devices(stderr) same as stdout
but normally for errors only.
Standard INPUT, OUTPUT and ERROR STREAM
 The standard devices are implemented as
files called standard streams in Python and
we can use them by using sys module.
 After importing sys module we can use
standard streams stdin, stdout, stderr

VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &


SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
“with” statement

 Python’s “with” statement for file handling is


very handy when you have two related
operations which you would like to execute as a
pair, with a block of code in between:
with open(filename[, mode]) as filehandle:
file_manipulation_statement
 The advantage of “with” is it will automatically
close the file after nested block of code. It
guarantees to close the file how nested block
exits even if any run time error occurs
Example
Binary file operations

 If we want to write a structure such as list or


dictionary to a file and read it subsequently
we need to use the Python module pickle.
Pickling is the process of converting structure
to a byte stream before writing to a file and
while reading the content of file a reverse
process called Unpickling is used to convert
the byte stream back to the original format.
Steps to perform binary file operations

 First we need to import the module called


pickle.
 This module provides 2 main functions:
 dump() : to write the object in file which is loaded
in binary mode
🞍 Syntax : dump(object_to_write, filehandle)

 load() : dumped data can be read from file using


load() i.e. it is used to read object from pickle file.
🞍 Syntax: object = load(filehandle)
Example: dump()

See the content is some kind


of encrypted format, and it is
not in complete readable
form
Example: load()
Absolute Vs Relative PATH
 To understand PATH we must be familiar with
the terms: DRIVE, FOLDER/DIRECTORY,
FILES.
 Our hard disk is logically divided into many
parts called DRIVES like C DRIVE, D DRIVE
etc.

VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &


SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
Absolute Vs Relative PATH
 The drive is the main container in which we
put everything to store.
 The naming format is : DRIVE_LETTER:
 For e.g. C: , D:
 Drive is also known as ROOT DIRECTORY.
 Drive contains Folder and Files.
 Folder contains sub-folders or files
 Files are the actual data container.

VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR &


SACHIN BHARDWAJ, PGT(CS), KV NO.1 TEZPUR
Absolute Vs Relative PATH
DRIVE
FOLDER

&
DRIVE/FOLDER/FILE HIERARCHY

C:\
DRIV E

SALES IT HR PROD
FOLDER FOLDER FOLDER R FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE
Absolute Path
 Absolute path is the full address of any file or
folder from the Drive i.e. from ROOT
FOLDER. It is like:
Drive_Name:\Folder\Folder…\filename
 For e.g. the Absolute path of file
REVENUE.TXT will be
 C:\SALES\2018\REVENUE.TXT
 Absolute path of SEC_12.PPT is
 C:\PROD\NOIDA\Sec_12.ppt
Relative Path

 Relative Path is the location of file/folder


from the current folder. To use Relative path
special symbols are:
 Single Dot ( . ) : single dot ( . ) refers to current
folder.
 Double Dot ( .. ) : double dot ( .. ) refers to parent
folder
 Backslash ( \ ) : first backslash before (.) and
double dot( .. ) refers to ROOT folder.
Relative addressing
Current working directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : SALES


WE WANT TO ACCESS SHEET.XLS FILE, THEN RELATIVE ADDRESS WILL BE

.\2019\SHEET.XLS
Relative addressing
Current working
directory
C:\
DRIVE

SALES IT HR PROD
FOLDER FOLDER FOLDER FOLDER

2018 2019 MEMBERS.DOC NOIDA DELHI


FOLDER FOLDER FOLDER FOLDER FOLDER

REVENUE.TXT SHEET.XLS SEC_8.XLS SEC_12.PPT


FILE FILE FILE FILE

SUPPOSE CURRENT WORKING DIRECTORY IS : DELHI


WE WANT TO ACCESS SEC_8.XLS FILE, THEN RELATIVE ADDRESS WILL BE
..\NOIDA\SEC_8.XLS
Getting name of current working
directory
import os
pwd = os.getcwd()
print("Current Directory :",pwd)

You might also like