UNIT IV Notes Python Programming(BCA614)
UNIT IV Notes Python Programming(BCA614)
Python Modules
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. We may
have a runnable code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the
specific module.
Example
In this example, we will create a module named as file.py which contains a function
func that contains a code to print some message on the console.
Let's create the module named as file.py.
1. #displayMsg prints a message to the name being passed.
2. def displayMsg(name)
3. print("Hi "+name);
Here, we need to include this module into our main module to call the method
displayMsg() defined in the module named file.
Loading the module in our python code
We need to load the module in our python code to use its functionality. Python
provides two types of statements as defined below.
1. The import statement
2. The from-import statement
Main.py:
1. from calculation import summation
2. #it will import only the summation() from calculation.py
3. a = int(input("Enter the first number"))
4. b = int(input("Enter the second number"))
5. print("Sum = ",summation(a,b)) #we do not need to specify the module name while
accessing summation()
Output:
Enter the first number10
Enter the second number20
Sum = 30
The from...import statement is always better to use if we know the attributes to be
imported from the module in advance. It doesn't let our code to be heavier. We can
also import all the attributes from a module by using *.
Consider the following syntax.
from <module> import *
Renaming a module
Python provides us the flexibility to import some module with a specific name so that
we can use this name to use that module in our python source file.
The syntax to rename a module is given below.
1. import <module-name> as <specific-name>
Example
1. #the module calculation of previous example is imported in this example as cal.
2. import calculation as cal;
3. a = int(input("Enter a?"));
4. b = int(input("Enter b?"));
5. print("Sum = ",cal.summation(a,b))
Output:
Enter a?10
Enter b?20
Sum = 30
Python math module is defined as the most famous mathematical functions, which
includes trigonometric functions, representation functions, logarithmic functions, etc.
Furthermore, it also defines two mathematical constants, i.e., Pie and Euler number,
etc.
Pie (n): It is a well-known mathematical constant and defined as the ratio of
circumstance to the diameter of a circle. Its value is 3.141592653589793.
Euler's number(e): It is defined as the base of the natural logarithmic, and its value is
2.718281828459045.
There are different math modules which are given below:
math.log()
This method returns the natural logarithm of a given number. It is calculated to the
base e.
Example
1. import math
2. number = 2e-7 # small value of of x
3. print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))
Output:
log(fabs(x), base) is : -6.698970004336019
math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.
Example
1. import math
2. x=13 # small value of of x
3. print('log10(x) is :', math.log10(x))
Output:
log10(x) is : 1.1139433523068367
math.exp()
This method returns a floating-point number after raising e to the given number.
Example
import math
number = 5e-2 # small value of of x
print('The given number (x) is :', number)
print('e^x (using exp() function) is :', math.exp(number)-1)
Output:
The given number (x) is : 0.05
e^x (using exp() function) is : 0.05127109637602412
math.pow(x,y)
This method returns the power of the x corresponding to the value of y. If value of x is
negative or y is not integer value than it raises a ValueError.
Example
1. import math
2. number = math.pow(10,2)
3. print("The power of number:",number)
Output:
The power of number: 100.0
math.floor(x)
This method returns the floor value of the x. It returns the less than or equal value to
x.
Example:
1. import math
2. number = math.floor(10.25201)
3. print("The floor value is:",number)
Output:
The floor value is: 10
math.ceil(x)
This method returns the ceil value of the x. It returns the greater than or equal value
to x.
1. import math
2. number = math.ceil(10.25201)
3. print("The floor value is:",number)
Output:
The floor value is: 11
math.fabs(x)
This method returns the absolute value of x.
import math
number = math.fabs(10.001)
print("The floor absolute is:",number)
Output:
The absolute value is: 10.001
math.factorial()
This method returns the factorial of the given number x. If x is not integral, it raises
a ValueError.
Example
1. import math
2. number = math.factorial(7)
3. print("The factorial of number:",number)
Output:
The factorial of number: 5040
math.modf(x)
This method returns the fractional and integer parts of x. It carries the sign of x is float.
Example
1. import math
2. number = math.modf(44.5)
3. print("The modf of number:",number)
Output:
The modf of number: (0.5, 44.0)
Python provides the several math modules which can perform the complex task in single-line
of code. In this tutorial, we have discussed a few important math modules.
random.random()
This function generates a random float number between 0.0 and 1.0.
random.randint()
This function returns a random integer between the specified integers.
random.choice()
This function returns a randomly selected element from a non-empty sequence.
Example
1. # importing "random" module.
2. import random
3. # We are using the choice() function to generate a random number from
4. # the given list of numbers.
5. print ("The random number from list is : ",end="")
6. print (random.choice([50, 41, 84, 40, 31]))
Output:
The random number from list is: 84
random.shuffle()
This function randomly reorders the elements in the list.
random.randrange(beg,end,step)
This function is used to generate a number within the range specified in its argument.
It accepts three arguments, beginning number, last number, and step, which is used
to skip a number in the range. Consider the following example.
1. # We are using randrange() function to generate in range from 100
2. # to 500. The last parameter 10 is step size to skip
3. # ten numbers when selecting.
4. import random
5. print ("A random number from range is : ",end="")
6. print (random.randrange(100, 500, 10))
Output:
A random number from range is : 290
Source
1. https://www.javatpoint.com/python-tutorial
2. https://www.w3schools.com/python/
3. https://www.tutorialspoint.com/python/index.htm
4. https://www.geeksforgeeks.org/python-programming-language/
19
random.seed()
This function is used to apply on the particular random number with the seed
argument. It returns the mapper value. Consider the following example.
1. # importing "random" module.
2. import random
3. # using random() to generate a random number
4. # between 0 and 1
5. print("The random number between 0 and 1 is : ", end="")
6. print(random.random())
7. # using seed() to seed a random number
8. random.seed(4)
Output:
The random number between 0 and 1 is : 0.4405576668981033
Python packages
The packages in python facilitate the developer with the application development
environment by providing a hierarchical directory structure where a package contains
subpackages,
modules, and sub-modules. The packages are used to categorize the application
level code efficiently.
We usually organize our files in different folders and subfolders based on some criteria, so
that they can be managed easily and efficiently. For example, we keep all our games in a
Games folder and we can even subcategorize according to the genre of the game or
something like that. The same analogy is followed by the packages in Python.
What is a Python Package?
Python Packages are a way to organize and structure your Python code into reusable
components. Think of it like a folder that contains related Python files (modules) that work
together to provide certain functionality. Packages help keep your code organized, make it
easier to manage and maintain, and allow you to share your code with others. They‟re like a
toolbox where you can store and organize your tools (functions and classes) for easy access
and reuse in different projects.
How to Create Package in Python?
Creating packages in Python allows you to organize your code into reusable and manageable
modules. Here‟s a brief overview of how to create packages:
Create a Directory: Start by creating a directory (folder) for your package. This
directory will serve as the root of your package structure.
Source
1. https://www.javatpoint.com/python-tutorial
2. https://www.w3schools.com/python/
3. https://www.tutorialspoint.com/python/index.htm
4. https://www.geeksforgeeks.org/python-programming-language/
20
Add Modules: Within the package directory, you can add Python
files (modules) containing your code. Each module should represent a
distinct functionality or component of your package.
Init File: Include an init .py file in the package directory. This file can be
empty or can contain an initialization code for your package. It signals to Python
that the directory should be treated as a package.
Subpackages: You can create sub-packages within your package by adding
additional directories containing modules, along with their own init .py files.
Importing: To use modules from your package, import them into your Python
scripts using dot notation. For example, if you have a module named module.py
inside a package named mypackage, you would import it like this: from
mypackage import module.
Distribution: If you want to distribute your package for others to use, you can
create a setup.py file using Python‟s setuptools library. This file defines metadata
about your package and specifies how it should be installed.
Code Example
Here‟s a basic code sample demonstrating how to create a simple Python
package:
1. Create a directory named mypackage.
2. Inside mypackage, create two Python files: module1.py and
module2.py.
3. Create an init .py file inside mypackage (it can be empty).
4. Add some code to the modules.
5. Finally, demonstrate how to import and use the modules from the
package.
Example: Now, let‟s create a Python script outside the mypackage directory
to import and use these modules:
# module1.py
def greet(name):
print(f"Hello, {name}!")
# module2.py
def add(a, b):
return a + b
from mypackage import module1, module2
# Using functions from module1
module1.greet("Alice")
# Using functions from module2
result = module2.add(3, 5)
print("The result of addition is:", result)
When you run the script, you should see the following output:
Example
Let's create a package named Employees in your home directory. Consider the
following steps.
1. Create a directory with name Employees on path /home.
2. Create a python source file with name ITEmployees.py on the path
/home/Employees.
ITEmployees.py
a. def getITNames():
b. List = ["John", "David", "Nick", "Martin"]
c. return List;
3. Similarly, create one more python file with name BPOEmployees.py and create a
function getBPONames()
4. Now, the directory Employees which we have created in the first step contains two
python modules. To make this directory a package, we need to include one more
file here, that is init .py which contains the import statements of the modules
defined in this directory.
init .py
1. from ITEmployees import getITNames
2. from BPOEmployees import getBPONames
Now, the directory Employees has become the package containing two python
modules. Here we must notice that we must have to create init .py inside a
directory to convert this directory to a package.
1. To use the modules defined inside the package Employees, we must have to
import this in our python source file. Let's create a simple python source file at
our home directory (/home) which uses the modules defined in this package. Test.py
1. import Employees
2. print(Employees.getNames())
Output:
['John', 'David', 'Nick', 'Martin']
We can have sub-packages inside the packages. We can nest the packages up to any
level depending upon the application requirements.
The following image shows the directory structure of an application Library
management system which contains three sub-packages as Admin, Librarian, and
Student. The sub-packages contain the python modules.
File handling in Python is a powerful and versatile tool that can be used to perform a wide range
of operations. However, it is important to carefully consider the advantages and disadvantages of
file handling when writing Python programs, to ensure that the code is secure, reliable, and
performs well.
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. The concept of file handling has stretched over
various other languages, but the implementation is either complicated or lengthy, like other
concepts of Python, this concept here is also easy and short. Python treats files differently as text or
binary and this is important. Each line of code includes a sequence of characters, and they form a
text file. Each line of a file is terminated with a special character, called the EOL or End of Line
characters like comma {,} or newline character. It ends the current line and tells the interpreter a
new one has begun. Let‟s start with the reading and writing files.
Advantages of File Handling in Python
Versatility: File handling in Python allows you to perform a wide range of operations,
such as creating, reading, writing, appending, renaming, and deleting files.
Flexibility: File handling in Python is highly flexible, as it allows you to work with
different file types (e.g. text files, binary files, CSV files, etc.), and to perform different
operations on files (e.g. read, write, append, etc.).
User–friendly: Python provides a user-friendly interface for file handling, making it easy
to create, read, and manipulate files.
Cross-platform: Python file-handling functions work across different platforms (e.g.
Windows, Mac, Linux), allowing for seamless integration and compatibility.
Disadvantages of File Handling in Python
Error-prone: File handling operations in Python can be prone to errors, especially if the
code is not carefully written or if there are issues with the file system (e.g. file
permissions, file locks, etc.).
Security risks: File handling in Python can also pose security risks, especially if the
program accepts user input that can be used to access or modify sensitive files on the
system.
Complexity: File handling in Python can be complex, especially when working with
more advanced file formats or operations. Careful attention must be paid to the code to
ensure that files are handled properly and securely.
Performance: File handling operations in Python can be slower than other programming
languages, especially when dealing with large files or performing complex operations.
For this article, we will consider the following “sample.txt” file as an example.
Hello world
SampleforSample
123 456
Python File Open
Before performing any operation on the file like reading or writing, first, we have to open that file.
For this, we should use Python‟s inbuilt function open() but at the time of opening, we have to
specify the mode, which represents the purpose of the opening file.
f = open(filename, mode)
Where the following mode is supported:
1. r: open an existing file for a read operation.
2. w: open an existing file for a write operation. If the file already contains some data,
then it will be overridden but if the file is not present then it creates the file as well.
3. a: open an existing file for append operation. It won‟t override existing data.
4. r+: To read and write data into the file. The previous data in the file will be overridden.
5. w+: To write and read data. It will override existing data.
6. a+: To append and read data from the file. It won‟t override existing data.
Working in Read mode
There is more than one way to How to read from a file in Python. Let us see how we can
read the content of a file in read mode.
Example 1: The open command will open the Python file in the read mode and the for loop
will print each line present in the file.
Python3
print (each)
Output:
Hello world
SampleforSample
123 456
Example 2: In this example, we will extract a string that contains all characters in the
Python file then we can use file.read().
Python3
print (file.read())
Output:
Hello world
SampleforSample
123 456
Example 3: In this example, we will see how we can read a file using the with statement in
Python.
Python3
# Python code to illustrate with()
data = file.read()
print(data)
Output:
Hello world
SampleforSample
123 456
Example 4: Another way to read a file is to call a certain number of characters like in the
following code the interpreter will read the first five characters of stored data and return it
as a string:
Python3
print (file.read(5))
Output:
Hello
Example 5: We can also split lines while reading files in Python. The split() function splits the variable
when space is encountered. You can also split using any characters as you wish.
# Python code to illustrate split() function
Python3
with open("sample.txt", "r") as file:
data = file.readlines()
word = line.split()
print (word)
Output:
['Hello', 'world']
['SampleforSample']
['123', '456']
Creating a File using the write() Function
Just like reading a file in Python, there are a number of ways to Writing to file in Python.
Let us see how we can write the content of a file using the write() function in Python.
Working in Write Mode
Let‟s see how to create a file and how the write mode works.
Example 1: In this example, we will see how the write mode and the write() function is
used to write in a file. The close() command terminates all the resources in use and frees the
system of this particular program.
Python3
file = open('geek.txt','w')
file.close()
Output:
This is the write commandIt allows us to write in a particular file
Example 2: We can also use the written statement along with the with() function.
Python3
f.write("Hello World!!!")
Output:
Hello World!!!
Working of Append Mode
Let us see how the append mode works.
Example: For this example, we will use the Python file created in the previous example.
Python3
# Python code to illustrate append() mode
file.close()
Output:
This is the write commandIt allows us to write in a particular fileThis will add this line
There are also various other commands in Python file handling that are used to handle
various tasks:
rstrip(): This function strips each line of a file off spaces from the right-hand side.
lstrip(): This function strips each line of a file off spaces from the left-hand side.
It is designed to provide much cleaner syntax and exception handling when you are
working with code. That explains why it‟s good practice to use them with a statement
where applicable. This is helpful because using this method any files opened will be closed
automatically after one is done, so auto-cleanup.
import os
def create_file(filename):
try:
f.write('Hello, world!\n')
except IOError:
try:
contents = f.read()
print(contents)
except IOError:
try:
f.write(text)
except IOError:
try:
os.rename(filename, new_filename)
except IOError:
def delete_file(filename):
try:
os.remove(filename)
except IOError:
filename = "example.txt"
new_filename = "new_example.txt"
create_file(filename)
read_file(filename)
read_file(filename)
rename_file(filename, new_filename)
read_file(new_filename)
delete_file(new_filename)
Output:
File example.txt created successfully.
Hello, world!
Text appended to file example.txt successfully.
Hello, world!
This is some additional text.
File example.txt renamed to new_example.txt successfully.
Hello, world!
This is some additional text.
File new_example.txt deleted successfully.
file1 = open("MyFile1.txt","a")
file2 = open(r"D:\Text\MyFile2.txt","w+")
Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2
file1 = open("MyFile.txt","a")
file1.close()
file1.write("Hello \n")
file1.writelines(L)
print(file1.read())
print()
file1.seek(0)
print(file1.readline())
print()
file1.seek(0)
print(file1.read(9))
print()
file1.seek(0)
print(file1.readline(9))
file1.seek(0)
# readlines function
print(file1.readlines())
print()
file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
file1 = open("myfile.txt","w")
file1.writelines(L)
file1.close()
# Append-adds at last
file1.write("Today \n")
file1.close()
file1 = open("myfile.txt","r")
print(file1.readlines())
print()
file1.close()
# Write-Overwrites
file1 = open("myfile.txt","w")#write mode
file1.write("Tomorrow \n")
file1.close()
file1 = open("myfile.txt","r")
print(file1.readlines())
print()
file1.close()
Output:
Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']
A file object allows us to use, access and manipulate all the user accessible files. One can
read and write any such files.
When a file operation fails for an I/O-related reason, the exception IOError is raised. This
includes situations where the operation is not defined for some reason, like seek() on a tty
device or writing a file opened for reading.
Files have the following methods:
open(): Opens a file in given access mode.
open(file_address, access_mode)
Examples of accessing a file: A file can be opened with a built-in function called
open(). This function takes in the file‟s address and the access_mode and returns a file
object.
There are different types of access_modes:
r: Opens a file for reading only
r+: Opens a file for both reading and writing
w: Opens a file for writing only
w+: Open a file for writing and reading.
a: Opens a file for appending
a+: Opens a file for both appending and reading
When you add 'b' to the access modes you can read the file in binary format rather than
the default text format. It is used when the file to be accessed is not in text.
read([size]): It reads the entire file and returns it contents in the form of a string. Reads
at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If
the size argument is negative or omitted, read all data until EOF is reached.
# Reading a file
#read()
text = f.read(10)
print(text)
f.close()
readline([size]): It reads the first line of the file i.e till a newline character or an EOF in
case of a file having a single line and returns a string. If the size argument is present and
non-negative, it is a maximum byte count (including the trailing newline) and an
incomplete line may be returned. An empty string is returned only when EOF is
encountered immediately.
#readline()
text = f.readline(20)
print(text)
f.close()
readlines([sizehint]): It reads the entire file line by line and updates each line to a list
which is returned.Read until EOF using readline() and return a list containing the lines
thus read. If the optional sizehint argument is present, instead of reading up to EOF,
whole lines totalling approximately sizehint bytes (possibly after rounding up to an
internal buffer size) are read.
# Reading a file
#readline()
text = f.readlines(25)
print(text)
f.close()
write(string): It writes the contents of string to the file. It has no return value. Due to
buffering, the string may not actually show up in the file until the flush() or close()
method is called.
# Writing a file
#write()
f.write(line)
f.close()
lines = f.read()
f.write(lines)
f.close()
lines = f.read()
f.write(lines)
f.close()
# Appending a file
f.write(lines)
f.close()
lines = f.read()
f.write(lines)
f.close()
# Writing a file
lines = f.readlines()
#writelines()
f.writelines(lines)
f.close()
tell(): It returns an integer that tells us the file object‟s position from the beginning of
the file in the form of bytes
lines = f.read(10)
#tell()
print(f.tell())
f.close()
lines = f.read(10)
print(lines)
#seek()
print(f.seek(2,2))
lines = f.read(10)
print(lines)
f.close()
flush(): Flush the internal buffer, like stdio„s fflush(). It has no return value. close()
automatically flushes the data but if you want to flush the data before closing the file
then you can use this method.
lines = f.read(10)
#flush()
f.flush()
print(f.read())
f.close()
fileno(): Returns the integer file descriptor that is used by the underlying
implementation to request I/O operations from the operating system.
#fileno()
print(f.fileno())
f.close()
isatty(): Returns True if the file is connected to a tty(-like) device and False if not.
#isatty()
print(f.isatty())
f.close()
next(): It is used when a file is used as an iterator. The method is called repeatedly. This
method returns the next input line or raises StopIteration at EOF when the file is open
for reading( behaviour is undefined when opened for writing).
#next()
try:
while f.next():
print(f.next())
except:
f.close()
truncate([size]): Truncate the file‟s size. If the optional size argument is present, the
file is truncated to (at most) that size. The size defaults to the current position. The
current file position is not changed. Note that if a specified size exceeds the file‟s
current size, the result is platform-dependent: possibilities include that the file may
remain unchanged, increase to the specified size as if zero-filled, or increase to the
specified size with undefined new content.
#truncate()
f.truncate(10)
f.close()
close(): Used to close an open file. A closed file cannot be read or written any more.
#close()
f.close()
Attributes:
closed: returns a boolean indicating the current state of the file object. It
returns true if the file is closed and false when the file is open.
encoding: The encoding that this file uses. When Unicode strings are written
to a file, they will be converted to byte strings using this encoding.
mode: The I/O mode for the file. If the file was created using the open()
built-in function, this will be the value of the mode parameter.
name: If the file object was created using open(), the name of the file.
newlines: A file object that has been opened in universal newline mode have
this attribute which reflects the newline convention used in the file. The
value for this attribute are “\r”, “\n”, “\r\n”, None or a tuple containing all the
newline types seen.
softspace: It is a boolean that indicates whether a space character needs to be
printed before another value when using the print statement.
print(f.closed)
print(f.encoding)
print(f.mode)
print(f.newlines)
print(f.softspace)
The fileinput module lets you loop over all the lines in a list of text files. Performance is quite
good, comparable to the performance of direct iteration on each file, since fileinput uses
internal buffering to minimize I/O. Therefore, you can use module fileinput for line-oriented
file input whenever you find the module‟s rich functionality convenient, without worrying
about performance. The input function is the main function of module fileinput, and the
module also provides a FileInput class that supports the same functionality as the module‟s
functions.
The linecache module lets you read a given line (specified by number) from a file with a given
name. The module keeps an internal cache, so if you need to read several lines from a file, the
operation is cheaper than opening and examining the file each time.Module linecache exposes the
following functions.
The struct module lets you pack binary data into a string, and then unpack the bytes of such a string
back into the data they represent. Such operations can be useful for various kinds of low-level
programming. Most often, you use module struct to interpret data records from binary.
StringIO and cStringIO – Work with text buffers using file-like API
Purpose: Work with text buffers using file-like API
StringIO provides a convenient means of working with text in memory using the file API (read,
write. etc.). There are two separate implementations. The cStringIO version is written in C for
speed, while StringIO is written in Python for portability. Using cStringIO to build large strings
can offer performance savings over some other string conctatenation techniques.
Example
Here are some pretty standard, simple, examples of using StringIO buffers:
# Find the best implementation available on this platform
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
# Writing to a buffer
output = StringIO()
output.write('This goes into the buffer. ')
print >>output, 'And so does this.'
read buffer
input = StringIO('Inital value for read buffer')
This example uses read(), but the readline() and readlines() methods are also available. The
StringIO class also provides a seek() method so it is possible to jump around in a buffer while
reading, which can be useful for rewinding if you are using some sort of look-ahead parsing
algorithm.
$ python stringio_examples.py
Real world applications of StringIO include a web application stack where various parts of the
stack may add text to the response, or testing the output generated by parts of a program which
typically write to a file.
The application we are building at work includes a shell scripting interface in the form of several
command line programs. Some of these programs are responsible for pulling data from the database
and dumping it on the console (either to show the user, or so the text can serve as input to another
command). The commands share a set of formatter plugins to produce a text representation of an
object in a variety of ways (XML, bash syntax, human readable, etc.). Since the formatters
normally write to standard output, testing the results would be a little tricky without the StringIO
module. Using StringIO to intercept the output of the formatter gives us an easy way to collect the
output in memory to compare against expected results.
References:
1. https://www.javatpoint.com/python-tutorial
2. https://www.w3schools.com/python/
3. https://www.tutorialspoint.com/python/index.htm
4. https://www.geeksforgeeks.org/python-programming-language