Python 214 275
Python 214 275
4.0 INTRODUCTION
• Modules and packages are the constructs in Python programming that promote code
modularization.
• The modularization (modular programming) refers to the process of breaking a large
programming task into separate, smaller, more manageable subtasks or modules.
• A module in Python programming allows us to logically organize the python code. A
module is a single source code file.
• The module in Python has the .py file extension. The name of the module will be the
name of the file.
• A python module can be defined as a python program file which contains a python
code including python functions, class, or variables.
• In other words, we can say that our Python code file saved with the extension (.py) is
treated as the module.
• In Python, packages allow us to create a hierarchical file directory structure of
modules. For example, mymodule.mod1 stands for a module mod1, in the package
mymodule.
• A Python package is a collection of modules which have a common purpose. In short,
modules are grouped together to forms packages.
• A file is a collection of related data that acts as a container of storage as data
permanently.
• The file processing refers to a process in which a program processes and accesses data
stored in files.
4.1
Python Programming Modules, Working with Files and Exception Handling
• A file is a computer resource used for recording data in a computer storage device.
The processing on a file is performed using read/write operations performed by
programs.
• Python supports file handling and allows users to handle files i.e., to read and write
files, along with many other file handling options, to operate on files.
• Python programming provides modules with functions that enable us to manipulate
text files and binary files. Python allows us to create files, update their contents and
also delete files.
• Files are named locations on disk to store related information. They are used to
permanently store data in a non-volatile memory (e.g. hard disk).
• A text file is a file that stores information in the term of a sequence of characters
(textual information), while a binary file stores data in the form of bits (0s and 1s) and
used to store information in the form of text, images, audios, videos etc.
• The file handling plays an important role when the data needs to be stored
permanently into the file. A file is a named location on disk to store related
information.
• We can access the stored information (non-volatile) after the program termination.
Python has several functions for creating, reading, updating, and deleting files.
• When an error occurs, or exception as we call it, Python will normally stop and
generate an error message. Exception in Python is nothing but errors which are
encountered at the run time.
• Exception Handling is the mechanism it is allows to handle errors very smartly while
the program is running.
4.1 MODULES
• Modules are primarily the (.py) files which contain Python programming code
defining functions, class, variables, etc. with a suffix .py appended in its file name. A
file containing .py python code is called a module.
• If we want to write a longer program, we can use file where we can do editing,
correction. This is known as creating a script. As the program gets longer, we may
want to split it into several files for easier maintenance.
• We may also want to use a function that we have written in several programs without
copying its definition into each program.
• In Python we can put definitions in a file and use them in a script or in an interactive
instance of the interpreter. Such a file is called a module.
4.1.1 Writing/Creating and Exploring Module
• Writing a module means simply creating a file which can contains python definitions
and statements. The file name is the module name with the extension .py. To include
module in a file, use ‘import’ statement.
• Follow the following steps to create modules:
1. Create a first file as a python program with extension as .py. This is your module
file where we can write a function which performs some task.
4.2
Python Programming Modules, Working with Files and Exception Handling
2. Create a second file in the same directory called main file where we can import the
module to the top of the file and call the function.
• Second file needs to be in the same directory so that Python knows where to find the
module since it’s not a built-in module.
Example: For creating a module. Type the following code and save it as p1.py.
def add(a, b):
"This function adds two numbers and return the result"
result = a + b
return result
def sub(a, b):
"This function subtract two numbers and return the result"
result = a - b
return result
def mul(a, b):
"This function multiply two numbers and return the result"
result = a * b
return result
def div(a, b):
"This function divide two numbers and return the result"
result = a / b
return result
Import the definitions inside a module:
import p1
print("Addition=" , p1.add(10,20))
print("Subtraction=" ,p1.sub(10,20))
print("Multiplication=" ,p1.mul(10,20))
print("division=" ,p1.div(10,20))
Output:
Addition= 30
Subtraction= -10
Multiplication= 200
division= 0.5
Exploring Modules:
• Modules in Python are simply Python files with a .py extension. The name of the
module will be the name of the file. A Python module can have a set of functions,
classes or variables defined and implemented.
• To exploring modules in Python the dir() function is used. For example, we have
defined a function add() in the module example that we had in the beginning.
4.3
Python Programming Modules, Working with Files and Exception Handling
(v) randint() Method: Returns a random number selected element from the
specified range.
Example:
import random
print random.randint(0,5) #output either 1,2,3,4 or 5
(vi) choice() Method: Returns a random element from the given sequence.
Example:
import random
MyChoice = random.choice(['1-Swimming', '2-Badminton',
'3-Cricket', '4-Basketball', '5-Hockey'])
print 'My choice is:', MyChoice #returns: My choice is :
4-Basketball
5. Statistics Module:
• Statistics module provides access to different statistics functions. Example includes
mean (average value), median (middle value), mode (most often value), standard
deviation (spread of values).
Example: For statistics module.
>>> import statistics
>>> statistics.mean([2,5,6,9]) # average
5.5
>>> import statistics
>>> statistics.median([1,2,3,8,9]) # central value
3
>>> statistics.median([1,2,3,7,8,9])
5.0
>>> import statistics
>>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6]) # repeated value
2
>>> import statistics
>>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153
(II) Functional Programming Modules:
• These modules provide functions and classes that support a functional programming
style and general operations on callable.
• Following are modules which comes under functional programming modules.
(i) itertools (functions creating iterators for efficient looping).
(ii) functools (higher-order functions and operations on callable objects).
(iii) operator (standard operators as functions).
1. itertools Module:
• Python programming itertools module provide us various ways to manipulate the
sequence while we are traversing it.
• Python itertools chain() function just accepts multiple iterable and return a single
sequence as if all items belongs to that sequence.
4.12
Python Programming Modules, Working with Files and Exception Handling
• Now, if we want to make some dedicated functions to double or triple a number then
we will have to define new functions as:
def multiplier(x, y):
return x * y
def doubleIt(x):
return multiplier(x, 2)
def tripleIt(x):
return multiplier(x, 3)
• But what happens when we need 1000 such functions? Here, we can use partial
functions:
from functools import partial
def multiplier(x, y):
return x * y
double = partial(multiplier, y=2)
triple = partial(multiplier, y=3)
print('Double of 2 is {}'.format(double(5)))
print('Triple of 5 is {}'.format(triple(5)))
Output:
Double of 5 is 10
Triple of 5 is 15
3. Operator Module:
• The operator module supplies functions that are equivalent to Python’s operators.
These functions are handy in cases where callables must be stored, passed as
arguments, or returned as function results.
• Functions supplied by the operator module are listed in following table:
Sr.
Function Signature/Syntax Behaves Like
No.
1. abs abs(a) abs(a)
2. add add(a,b) a+b
3. and_ and_(a,b) a&b
4. div div(a,b) a/b
5. eq eq(a,b) a==b
6. gt gt(a,b) a>b
7. invert, inv invert(a), inv(a) ~a
8. le le(a,b) a<=b
9. lshift lshift(a,b) a<<b
10. lt lt(a,b) a<b
11. mod mod(a,b) a%b
contd. …
4.14
Python Programming Modules, Working with Files and Exception Handling
Datetime Module:
• A date in Python is not a data type of its own, but we can import a module
named datetime to work with dates as date objects.
Example: Import the datetime module and display the current date:
import datetime
x = datetime.datetime.now()
print(x)
Output:
2021-07-24 12:41:12.701464
• The date contains year, month, day, hour, minute, second, and microsecond.
The datetime module has many methods to return information about the date object.
Example: Return the year and name of weekday:
import datetime
x = datetime.datetime.now()
print(x.year)
print(x.strftime("%A"))
Output:
2021
Saturday
Creating Date Objects:
• To create a date, we can use the datetime() class (constructor) of the datetime module.
• The datetime() class requires three parameters to create a date: year, month, day.
Example: Create a date object:
import datetime
x = datetime.datetime(2020, 5, 17)
print(x)
Output:
2021-07-24 00:00:00
4.2 PACKAGES
• Suppose we have developed a very large application that includes many modules. As
the number of modules grows, it becomes difficult to keep track of them all as they
have similar names or functionality.
• It is necessary to group and organize them by some mean which can be achieved by
packages.
• A package is a hierarchical file directory structure that defines a single Python
application environment that consists of modules and subpackages and sub-
subpackages and so on.
• Packages allow for a hierarchical structuring of the module namespace using dot
notation. Packages are a way of structuring many packages and modules which help
in a well-organized hierarchy of data set, making the directories and modules easy to
access.
• A package is a collection of Python modules, i.e., a package is a directory of Python
modules containing an additional _ _init_ _.py file (For example: Phone/_ _init_ _.py).
4.16
Python Programming Modules, Working with Files and Exception Handling
p1.py
p2.py
Fig. 4.1
• Here, mypkg a folder /directory which consist of p1.py and p2.py. We can refer these
two modules with dot notation (mypkg.p1, mypkg.p2) and import them with the one of
the following syntaxes:
Syntax 1: import <module_name>[, <module_name> ...]
Example:
>>> import mypkg.p1,mypkg.p2
>>> mypkg.p1.m1()
first module
>>> p1.m1()
Syntax 2: from <module_name> import <name(s)>
Example:
>>> from mypkg.p1 import m1
>>> m1()
first module
>>>
Syntax 3: from <module_name> import <name> as <alt_name>
Example:
>>> from mypkg.p1 import m1 as function
>>> function()
first module
>>>
4.17
Python Programming Modules, Working with Files and Exception Handling
NumPy:
• NumPy is the fundamental package for scientific computing with Python. NumPy
stands for "Numerical Python". It provides a high-performance multidimensional
array object, and tools for working with these arrays.
• An array is a table of elements (usually numbers), all of the same type, indexed by a
tuple of positive integers and represented by a single variable. NumPy's array class is
called ndarray. It is also known by the alias array.
• In NumPy arrays, the individual data items are called elements. All elements of an
array should be of the same type. Arrays can be made up of any number of
dimensions.
• In NumPy, dimensions are called axes. Each dimension of an array has a length which
is the total number of elements in that direction.
• The size of an array is the total number of elements contained in an array in all the
dimension. The size of NumPy arrays are fixed; once created it cannot be changed
again.
• Numpy arrays are great alternatives to Python Lists. Some of the key advantages of
Numpy arrays are that they are fast, easy to work with, and give users the opportunity
to perform calculations across entire arrays.
SciPy:
• SciPy is a library that uses NumPy for more mathematical functions. SciPy uses
NumPy arrays as the basic data structure, and comes with modules for various
commonly used tasks in scientific programming, including linear algebra, integration
(calculus), ordinary differential equation solving, and signal processing.
Matplotlib:
• The matplotlib.pyplot is a plotting library used for 2D graphics in python
programming language. It can be used in python scripts, shell, web application servers
and other graphical user interface toolkits.
• There are various plots which can be created using python matplotlib like bar graph,
histogram, scatter plot, area plot, pie plot.
Pandas:
• Pandas is an open-source Python Library providing high-performance data
manipulation and analysis tool using its powerful data structures.
• It is built on the Numpy package and its key data structure is called the DataFrame.
DataFrames allow you to store and manipulate tabular data in rows of observations
and columns of variables.
• As we know, a module can contain multiple objects, such as classes, functions, etc.
A package can contain one or more relevant modules.
• Physically, a package is actually a folder containing one or more module files. Let's
create a package named MyPkg, using the following steps:
Step 1: Create a folder MyPkg on,
C:\Users\Meenakshi\AppData\Local\Programs\Python\Python37\”.
Create modules Message.py and Mathematics.py with following code:
Message.py
def SayHello(name):
print("Hello " + name)
return
Mathematics.py
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
Step 2: Create an empty _ _init_ _.py file in the MyPkg folder. The package folder
contains a special file called _ _init_ _.py, which stores the package's content. It serves
two purposes:
(i) The Python interpreter recognizes a folder as the package if it contains
_ _init_ _.py file.
(ii) _ _init_ _.py exposes specified resources from its modules to be imported.
An empty _ _init_ _.py file makes all functions from above modules available when this
package is imported. Note that _ _init_ _.py is essential for the folder to be recognized
by Python as a package. We can optionally define functions from individual modules
to be made available.
Step 3: Create P1.py file in MyPkg folder and write following code:
from MyPkg import Mathematics
from MyPkg import Message
greet.SayHello("Meenakshi")
x=functions.power(3,2)
print("power(3,2) : ", x)
Output:
Hello Meenakshi
power(3,2) : 9
4.20
Python Programming Modules, Working with Files and Exception Handling
# faculty.py
class Faculty:
def __init__(self, faculty):
self.name = faculty['name']
self.subject = faculty['subject']
def get_faculty_details(self):
return f"Name: {self.name}\nSubject: {self.subject}"
• We have the above in the student.py and faculty.py files. Let's create another file to
access those classed inside it. Now, inside the package directory create a file
named testing.py and include the following code:
# testing.py
# importing the Student and Faculty classes from respective files
from student import Student
from faculty import Faculty
# creating dicts for student and faculty
student_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'}
faculty_dict = {'name': 'Emma', 'subject': 'Programming'}
# creating instances of the Student and Faculty classes
student = Student(student_dict)
faculty = Faculty(faculty_dict)
# getting and printing the student and faculty details
print(student.get_student_details())
print()
print(faculty.get_faculty_details())
Output:
Name: John
Gender: Male
Year: 3
Name: Emma
Subject: Programming
• We have seen how to create and to access a package in Python. And this is a simple
package. There might be plenty of sub-packages and files inside a package. Let's see
how to access subpackage modules.
4.22
Python Programming Modules, Working with Files and Exception Handling
o __init__.py
o Subpackage (student)
__init__.py
main.py
...
o testing.py
• Copy the above student code and place it here. Now, let's see how to access it in
the testing.py file. Add the following in the testing.py file.
Example:
# testing.py
from student.main import Student
# creating dicts for student
student_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'}
# creating instances of the Student class
student = Student(student_dict)
# getting and printing the student details
print(student.get_student_details())
Output: After running testing.py.
Name: John
Gender: Male
Year: 3
Example: For NumPy with array object.
>>> import numpy as np
>>> a=np.array([1,2,3]) # one dimensional array
>>> print(a)
[1 2 3]
>>> arr=np.array([[1,2,3],[4,5,6]]) # two dimensional array
>>> print(arr)
[[1 2 3]
[4 5 6]]
>>> type(arr)
<class 'numpy.ndarray'>
>>> print("No. of dimension: ", arr.ndim)
4.23
Python Programming Modules, Working with Files and Exception Handling
No. of dimension: 2
>>> print("Shape of array: ", arr.shape)
Shape of array: (2, 3)
>> >print("size of array: ", arr.size)
size of array: 6
>>> print("Type of elements in array: ", arr.dtype)
Type of elements in array: int32
>>> print("No of bytes:", arr.nbytes)
No of bytes: 24
Example 1: Using linalg sub package of SciPy.
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1., 2.], [3., 4.]])
>>> linalg.inv(a) # find inverse of array
array([[-2. , 1. ],
[ 1.5, -0.5]])
>>>
Example 2: Using linalg sub package of SciPy.
>>> import numpy as np
>>> from scipy import linalg
>>> a = np.array([[1,2,3], [4,5,6], [7,8,9]])
>>> linalg.det(a) # find determinant of array
0.0
>>>
Example 3: For line plot.
>>> from matplotlib import pyplot as plt
>>> x=[2,4,8,10]
>>> y=[2,8,8,2]
>>> plt.plot(x,y)
[<matplotlib.lines.Line2D object at 0x02E69B70>]
>>> plt.show()
Output:
4.24
Python Programming Modules, Working with Files and Exception Handling
>>> index=['a','b','c','d','e']
>>> si=pd.Series(data,index)
>>> si
a 10
b 20
c 30
d 40
e 50
dtype: int64
>>>
• To create a new file in Python, use the open() method, with one of the following
parameters.
"x" - create - will create a file, returns an error if the file exist.
"a" - append - will create a file if the specified file does not exist.
"w" - write - will create a file if the specified file does not exist.
Example: Create a file called "xyz.txt":
f = open("xyz.txt", "x") # Here a new empty file is created
Example: Create a new file if it does not exist:
f = open("xyz.txt", "w")
Write to an Existing File
• To write to an existing file, you must add a parameter to the open() function
"a" - Append - will append to the end of the file.
"w" - Write - will overwrite any existing content.
Example: Open the file "demofile.txt" and append content to the file:
f = open("abc.txt", "a")
f.write("Now you can append line to a file")
Example:
file = open("testfile.txt","w")
file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")
• There are two types of files that can be handled in python, normal text files and binary
files.
o Text files: In this type of file, Each line of text is terminated with a special
character called EOL (End of Line), which is the new line character (‘\n’) in Python
by default.
o Binary files: In this type of file, there is no terminator for a line and the data is
stored after converting it into machine understandable binary language.
Accessing File Contents using Standard Library Functions:
• Once, a file is opened and we will have one file object, we can get various information
related to that file. Here, is a list of all attributes related to file object:
Sr.
Attribute Description Example
No.
1. file.closed Returns true if file is closed, >>> f=open("abc.txt")
false otherwise. >>> f.closed
False
contd. …
4.27
Python Programming Modules, Working with Files and Exception Handling
o access_mode: The access_mode determines the mode in which the file has to be
opened, i.e., read, write, append, etc. A complete list of possible values is given
below in the table. This is an optional parameter and the default file access mode
is read (r).
o buffering: If the buffering value is set to 0, no buffering takes place. If the
buffering value is 1, line buffering is performed while accessing a file. If you
specify the buffering value as an integer greater than 1, then buffering action is
performed with the indicated buffer size. If negative, the buffer size is the system
default(default behavior).
• The file can be open in Text mode or Binary mode.
(i) The text mode returns strings while reading from the file. The default is reading
in text mode.
(ii) The binary mode returns bytes and this is the mode to be used when dealing with
non-text files like image or executable files.
• The text and binary modes are used in conjunction with the r, w, and a modes. The list
of all the modes used in Python are given in following table:
Sr.
Mode Description
No.
1. r Opens a file for reading only. The file pointer is placed at the
beginning of the file. This is the default mode.
2. rb Opens a file for reading only in binary format. The file pointer is
placed at the beginning of the file. This is the default mode.
3. r+ Opens a file for both reading and writing. The file pointer placed at
the beginning of the file.
4. rb+ Opens a file for both reading and writing in binary format. The file
pointer placed at the beginning of the file.
5. w Opens a file for writing only. Overwrites the file if the file exists. If the
file does not exist, creates a new file for writing.
6. wb Opens a file for writing only in binary format. Overwrites the file if
the file exists. If the file does not exist, creates a new file for writing.
7. w+ Opens a file for both writing and reading. Overwrites the existing file
if the file exists. If the file does not exist, creates a new file for reading
and writing.
8. wb+ Opens a file for both writing and reading in binary format. Overwrites
the existing file if the file exists. If the file does not exist, creates a new
file for reading and writing.
contd. …
4.29
Python Programming Modules, Working with Files and Exception Handling
9. a Opens a file for appending. The file pointer is at the end of the file if
the file exists. That is, the file is in the append mode. If the file does
not exist, it creates a new file for writing.
10. ab Opens a file for appending in binary format. The file pointer is at the
end of the file if the file exists. That is, the file is in the append mode.
If the file does not exist, it creates a new file for writing.
11. a+ Opens a file for both appending and reading. The file pointer is at the
end of the file if the file exists. The file opens in the append mode. If
the file does not exist, it creates a new file for reading and writing.
12. ab+ Opens a file for both appending and reading in binary format. The file
pointer is at the end of the file if the file exists. The file opens in the
append mode. If the file does not exist, it creates a new file for reading
and writing.
13. t Opens in text mode (default).
14. b Opens in binary mode.
15. + Opens a file for updating (reading and writing).
Example: For different modes of opening a file.
f = open("test.txt") # opening in r mode (reading only)
f = open("test.txt",'w') # opens in w mode (writing mode)
f = open("img.bmp",'rb+') # read and write in binary mode
2. close() Function:
• When the all operations related to the file are complete, then we need to close the file.
The close() function of a file object flushes any unwritten information and closes the
file object, after which no more writing can be done.
• Python automatically closes a file when the reference object of a file is reassigned to
another file. It is a good practice to use the close() function to close a file.
Syntax: fileObject.close()
Example:
# Open a file
f = open("test.txt", "w")
print ("Name of the file: ", f.name)
# Close opened file
f.close()
Output:
Name of the file: test.txt
3. Reading and Writing Files:
• The methods read() and write() are used to read and write files.
4.30
Python Programming Modules, Working with Files and Exception Handling
• For a list of string elements, each string is inserted in the text file. Used to insert
multiple strings at a single time.
File_object.writelines(L) for L = [str1, str2, str3]
Example: For writelines() method.
fruits=["Orange\n","Banana\n","Apple\n"]
f=open("sample.txt",mode="w+",encoding="utf-8")
f.writelines(fruits)
f.close()
f=open("sample.txt","r")
print(f.read())
Output:
Orange
Banana
Apple
Reading Data From File:
• To read a file in python, we must open the file in reading mode (r or r+).
• There are following three ways to read data from a text file:
1. read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified,
reads the entire file.
Syntax: File_object.read([n])
Example: for read() method.
f=open("sample.txt","r")
print(f.read(5)) # read first 5 data
print(f.read(5)) # read next five data
print(f.read()) # read rest of the file
print(f.read())
Output:
first
line
second line
third line
2. readline(): Reads a line of the file and returns in form of a string. For specified n,
reads at most n bytes. However, does not reads more than one line, even if n
exceeds the length of the line.
Syntax: File_object.readline([n])
4.32
Python Programming Modules, Working with Files and Exception Handling
7. os.rename(current,new) os.rename("sample.txt",
Rename a file.
"sample1.txt")
8. os.remove(file_name) Delete a file. os.remove("sample.txt")
9. os.mkdir() Creates a single os.mkdir("testdir")
subdirectory.
10. os.chdir(path) Change the os.chdir("d:\IT")
current working
directory to
path.
Example: For handling files through OS module.
import os
os.getcwd()
print("***Contents of Present working directory***\n ", os.listdir())
print(os.path.isfile("sample.txt"))
print(os.path.isdir("sample.txt"))
***Contents of Present working directory***
['DLLs', 'Doc', 'etc', 'file1.txt', 'include', 'Lib', 'libs',
'LICENSE.txt', 'mypkg', 'NEWS.txt', 'p1.py', 'p2.py', 'python.exe',
'python3.dll', 'python37.dll', 'pythonw.exe', 'sample.txt', 'Scripts',
'share', 'tcl', 'test.py', 'Tools', 'vcruntime140.dll', '_ _pycache_ _']
True
False
4.36
Python Programming Modules, Working with Files and Exception Handling
• The reference points are 0 (the beginning of the file and is default), 1 (the current
position of file) and 2 (the end of the file).
• The f.tell() returns an integer giving the file object’s current position in the file
represented as number of bytes from the beginning of the file when in binary
mode and an opaque number when in text mode.
• In other words, the tell() is used to find the current position of the file pointer in the
file while the seek() used to move the file pointer to the particular position.
Example 1: For file position.
f=open("sample.txt","r")
print(f.tell())
print(f.read())
print(f.tell())
print(f.read()) # print blank line
print(f.seek(0))
print(f.read())
Output:
0
first line
second line
third line
37
0
first line
second line
third line
>>>
Example 2:
fruits=["Orange\n","Banana\n","Apple\n"]
f=open("sample.txt",mode="w+",encoding="utf-8")
for fru in fruits:
f.write(fru)
print("Tell the byte at which the file cursor is:",f.tell())
f.seek(0)
for line in f:
print(line)
Output:
Tell the byte at which the file cursor is: 23
Orange
Banana
Apple
4.38
Python Programming Modules, Working with Files and Exception Handling
Example 3:
# Open a file
f = open("test.txt", "r+")
str = f.read(18)
print ("Read String is: ", str)
# Check current position
position = f.tell()
print ("Current file position: ", position)
# Reposition pointer at the beginning once again
position = f.seek(0, 0)
str = f.read(18)
print ("Again read String is: ", str)
# Close opened file
f.close()
Output:
Read String is: Python programming
Current file position: 18
Again read String is: Python programming
4.39
Python Programming Modules, Working with Files and Exception Handling
Output:
File : '/'
Absolute : True
Is File? : False
Is Dir? : True
Is Link? : False
Mountpoint? : True
Exists? : True
Link Exists? : True
File : './broken_link'
Absolute : False
Is File? : False
Is Dir? : False
Is Link? : True
Mountpoint? : False
Exists? : False
Link Exists? : True
• The copyfile() method makes use of lower-level function copyfileobj() below. It takes
file names as arguments, opens them and passes file handles to copyfileobj().
• In this method, one optional third argument can use to specify the buffer length. It’ll
then open the file for reading in chunks of the specified buffer size. However, the
default behavior is to read the entire file in one go.
Syntax: copyfile(source_file, destination_file)
Example: Sample code for copy file.
from shutil import copyfile
from sys import exit
source = input("Enter source file with full path: ")
target = input("Enter target file with full path: ")
# adding exception handling
try:
copyfile(source, target)
except IOError as e:
print("Unable to copy file. %s" % e)
exit(1)
except:
print("Unexpected error:", sys.exc_info())
exit(1)
print("\nFile copy done!\n")
while True:
print("Do you like to print the file ? (y/n): ")
check = input()
if check == 'n':
break
elif check == 'y':
file = open(target, "r")
print("\nHere follows the file content:\n")
print(file.read())
file.close()
print()
break
else:
continue
4.45
Python Programming Modules, Working with Files and Exception Handling
4.47
Python Programming Modules, Working with Files and Exception Handling
split() Method:
• The os.path.split() method splits a path, which is passed as an argument, into a
directory name and a base name and returns them as a tuple.
• The following example splits the joined path obtained in the previous example:
>>> import os.path
>>> os.path.split(join_dir)
('/home','testfile')
splitdrive() Method:
• The splitdrive() method is used to split the drive name and the path name of the
argument passed in the method.
• The following examples illustrates the use of the splitdrive() method in both Unix and
Windows versions:
o Unix Version:
>>> import os.path
>>> os.path.splitdrive('/home/testfile')
(' ', '/home/ testfile')
o Windows Version:
>>> import os.path
>>> os.path.splitdrive('c:/Python')
('c:', '/Python')
Table 4.2: The Information Methods of the os.path Module
Method Description
getsize(file_name) Returns the size of a file in bytes
getatime(file_name) Returns the time when a file was last accessed
getmtime(file_name) Returns the time when a file was last modified
splitext() Method:
• The splitext method separates the first name and the extension name of a filename.
Consider the following code:
>>> import os.path
>>> os.path.splitext('testfile.txt')
('testfile', '.txt')
• Let (name be a complete path to a file, say
/usr/home/hp1/scripting/python/intro/hw.py
4.50
Python Programming Modules, Working with Files and Exception Handling
• Occasionally you need to split such a filepath into the basename hw.py and the
directory name /usr/home/hpl/scripting/python/intro. In Python this is accomplished
by,
basename = os.path.basename(fname)
dirname = os.path.dirname(fname)
# or
dirname, basename = os.path.split(fname)
• The extension is extracted by the as path.split ext function,
root, extension = os.path.splitext(fname)
• Yielding '.py' for extension and the rest of f name for root.
• The extension without the leading dot is easily obtained by as,
path split ext (fname) 11] [1:].
• Changing some arbitrary extension of a file with name f to a new extension ext can be
done by,
newfile = os.path.splitext(f)[0] + ext
• Here is a specific example:
>>> f = '/some/path/case2.data_source'
>>> moviefile = os.path.basename(os.path.splitext(f)[0] + '.mpg')
>>> moviefile
'case2.mpg'
4.4 DIRECTORIES
• A directory or folder is nothing more than a location on a disk used for storing
information about files.
• All directories in Python are organized into a hierarchical structure that you can
imagine as a family tree.
• A directory or folder is a collection of files and sub directories.
• Python has the os module, which provides us with many useful methods to work with
directories (and files as well).
• All files are contained within various directories, and Python has no problem handling
these too.
• The os module has several methods that help us to create, remove, and change
directories.
• The os module contains the functions mkdir() for creating directories and chdir() for
moving to directories.
4.51
Python Programming Modules, Working with Files and Exception Handling
Directory
File File
File
Syntax: os.chdir(“dirname”)
Example:
>>> import os
>>> os.getcwd()
'C:\\Users\\Meenakshi\\AppData\\Local\\Programs\\Python\\Python37'
>>> os.chdir("d:\IT")
>>> os.getcwd()
'd:\\IT'
>>>
• If the directory is not empty then we will get the “The directory is not empty” error. To
remove a directory, first remove all the files inside it using os.remove() method.
>>> os.chdir("C:\\Users\\Meenakshi\\AppData\\Local\\Programs
\\Python\\Python37")
>>> os.rmdir("mydir1")
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
os.rmdir("mydir1")
OSError: [WinError 145] The directory is not empty: 'mydir1'
>>> os.chdir("C:\\Users\\Meenakshi\\AppData\\Local\\Programs
\\Python\\Python37\mydir1")
>>> os.listdir()
['sample.txt']
>>> os.remove("sample.txt")
>>> os.listdir()
[]
>>> os.chdir("C:\\Users\\Meenakshi\\AppData\\Local\\Programs
\\Python\\Python37")
>>> os.rmdir("mydir1")
>>>
• In order to remove a non-empty directory we can use the rmtree() method inside
the shutil module.
>>> import shutil
>>> shutil.rmtree('test')
PROGRAMS
Program 1: Program to create a simple file and write some content in it.
print("Enter 'x' for exit.");
filename = input("Enter file name to create and write content: ");
if filename == 'x':
exit();
else:
c = open(filename, "w");
print("\nThe file,",filename,"created successfully!");
4.54
Python Programming Modules, Working with Files and Exception Handling
Program 2: Program to open a file in write mode and append some content at the end of a
file.
print("Enter 'x' for exit.");
filename = input("Enter file name to append content: ");
if filename == 'x':
exit();
else:
c=open(filename, "a+");
print("Enter sentences to append on the file: ");
sent1=input();
c.write("\n");
c.write(sent1);
c.close();
print("\nContent appended to file.!!");
Output:
Enter 'x' for exit.
Enter file name to append content: file1
Enter sentences to append on the file:
good afternoon
Content appended to file.!!
4.55
Python Programming Modules, Working with Files and Exception Handling
Program 3: Program to open a file in read mode and print number of occurrences of
characters ‘a’.
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
Output:
Enter file name: file1
Enter letter to be searched:o
Occurrences of the letter:
7
Program 4: Program to read the contents of a file.
a=str(input("Enter the name of the file with .txt extension:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
print(line)
line=file2.readline()
file2.close()
Output:
Enter the name of the file with .txt extension: data1.txt
Program 5: Program to count the number of words and lines in a text file.
fname = input("Enter file name: ")
num_words = 0
lines=0
with open(fname, 'r') as f:
for line in f:
words = line.split()
num_words += len(words)
lines += 1
print("Number of words:")
4.56
Python Programming Modules, Working with Files and Exception Handling
print(num_words)
print("Number of lines:")
print(num_lines)
read.txt
Contents of file:
Hello world
Output:
Enter file name: data1.txt
Number of words:
2
Number of lines:
1
Program 6: Program to count the occurrences of a word in a text file.
fname = input("Enter file name: ")
word=input("Enter word to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
if(i==word):
k=k+1
print("Occurrences of the word:")
print(k)
read.txt
Let Contents of file:
hello world hello
hello
Output:
Enter file name: test.txt
Enter word to be searched:hello
Occurrences of the word:
3
Program 7: Program to copy the contents of one file into another.
with open("test.txt") as f:
with open("out.txt", "w") as f1:
for line in f:
f1.write(line)
4.57
Python Programming Modules, Working with Files and Exception Handling
Program 8: Program to reads a text file and counts the number of times a certain letter
appears in the text file.
fname = input("Enter file name: ")
l=input("Enter letter to be searched:")
k = 0
with open(fname, 'r') as f:
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
k=k+1
print("Occurrences of the letter:")
print(k)
read.txt:
Case 1:
Contents of file:
hello world hello
hello
Output:
Enter file name: out.txt
Enter letter to be searched:o
Occurrences of the letter:
5
Program 9: Program to read a file and capitalize the first letter of every word in the file.
fname = input("Enter file name: ")
with open(fname, 'r') as f:
for line in f:
l=line.title()
print(l)
read.txt:
Case 1:
Contents of file:
hello world
hello
Output:
Enter file name: read.txt
Hello World
Hello
4.58
Python Programming Modules, Working with Files and Exception Handling
Metacharacter Description
^ Matches the start of the string.
. Matches a single character, except a newline.
But when used inside square brackets, a dot is matched.
[] A bracket expression matches a single character from the ones
inside it.
[abc] matches ‘a’, ‘b’, and ‘c’.
[a-z] matches characters from ‘a’ to ‘z’.
[a-cx-z] matches ‘a’, ’b’, ’c’, ’x’, ’y’, and ‘z’.
[^ ] Matches a single character from those except the ones mentioned in
the brackets[^abc] matches all characters except ‘a’, ‘b’ and ‘c’.
contd. …
4.60
Python Programming Modules, Working with Files and Exception Handling