V Semester
Course 15 B : Application Development using Python
UNIT-II Files: File Objects, File Built-in Function [ open() ], File Built-in
Methods, File Built-in Attributes, Standard Files, Command-line Arguments,
File System, File Execution Exceptions: Exceptions in Python, Detecting and
Handling Exceptions, Context Management, Exceptions as Strings, Raising
Exceptions, Assertions, Standard Exceptions, Creating Exceptions, Why
Exceptions (Now)?, Why Exceptions at All?, Exceptions and the sys Module,
Related Modules Modules: Modules and Files, Namespaces, Importing
Modules, Importing Module Attributes, Module Built-in Functions, Packages,
Other Features of Modules
File Handling in Python
File handling involves interacting with files on your computer to read data
from them or write data to them. Python provides several built-in
functions and methods for creating, opening, reading, writing, and closing
files.
Opening a File in Python
To perform any file operation, the first step is to open the file. Python's built-in
open() function is used to open files in various modes, such as reading, writing,
and appending.
Syntax:
file=open(“filename”,”mode”)
Where,
filename is the name of the file to open and
mode is the mode in which the file is opened
File Opening Modes
Following are the file opening modes −
[Link]. Modes & Description
r
1
Opens a file for reading only. The file pointer is placed at the beginning of the file.
This is the default mode.
rb
2
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.
r+
3
Opens a file for both reading and writing. The file pointer placed at the beginning of
the file.
rb+
4
Opens a file for both reading and writing in binary format. The file pointer placed at
the beginning of the file.
w
5
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 b
Opens the file in binary mode
7 t
Opens the file in text mode (default)
8 +
open file for updating (reading and writing)
wb
9
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.
w+
10 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.
wb+
11 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.
a
12 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.
ab
13 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.
a+
14 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.
ab+
15 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.
16 x
open for exclusive creation, failing if the file already exists
Once a file is opened and you have one file object, you can get various
information related to that file.
Ex:
# Opening a file in read mode
file = open("[Link]", "r")
# Opening a file in write mode
file = open("[Link]", "w")
# Opening a file in append mode
file = open("[Link]", "a")
# Opening a file in binary read mode
file = open("[Link]", "rb")
Reading a File in Python
Reading a file in Python involves opening the file in a mode that allows for
reading and then using various methods to extract the data from the file.
Python provides several methods to read data from a file –
read() − Reads the entire file.
readline() − Reads one line at a time.
readlines − Reads all lines into a list.
Example: Using read() method
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Example: Using readline() method
with open("[Link]", "r") as file:
line = [Link]()
while line: print(line, end='')
line = [Link]()
Example: Using readlines() method
with open("[Link]", "r") as file:
lines = [Link]()
for line in lines:
print(line, end='')
Writing to a File in Python
It opens the file in a mode that allows writing, and then using various
methods to add content to the file.
To write data to a file, use the write() or writelines() methods. When
opening a file in write mode ('w'), the file's existing content is erased.
Example: Using the write() method
with open("[Link]", "w") as file:
[Link]("Hello, World!")
print ("Content added Successfully!!")
Example: Using the writelines() method
We are using the writelines() method to take a list of strings and writes
each string to the file. It is useful for writing multiple lines at once –
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("[Link]", "w") as file:
[Link](lines)
print ("Content added Successfully!!")
Closing a File in Python
We can close a file in Python using the close() method. Closing a file is an
essential step in file handling to ensure that all resources used by the file
are properly released. It is important to close files after operations are
completed to prevent data loss and free up system resources.
Example
file = open("[Link]", "w")
[Link]("This is an example.")
[Link]()
print ("File closed successfully!!")
Python Exception Handling
Python Exception Handling handles errors that occur during the execution
of a program. Exception handling allows to respond to the error, instead of
crashing the running program. It enables you to catch and manage errors,
making your code more robust and user-friendly.
# Simple Exception Handling Example
n = 10
try:
res = n / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Can't be divided by zero!")
Syntax and Usage
Exception handling in Python is done using the try, except, else and finally
blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
try Block: try block lets us test a block of code for errors. Python will
"try" to execute the code in this block. If an exception occurs, execution
will immediately jump to the except block.
except Block: except block enables us to handle the error or
exception. If the code inside the try block throws an error, Python
jumps to the except block and executes it. We can handle specific
exceptions or use a general except to catch all exceptions.
else Block: else block is optional and if included, must follow all
except blocks. The else block runs only if no exceptions are raised in
the try block. This is useful for code that should execute if the try block
succeeds.
finally Block: finally block always runs, regardless of whether an
exception occurred or not. It is typically used for cleanup operations
(closing files, releasing resources).
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
OUTPUT:
You can't divide by zero!
Execution complete.
Python Catching Exceptions
When working with exceptions in Python, we can handle errors more
efficiently by specifying the types of exceptions we expect. This can make
code both safer and easier to debug.
Catching Specific Exceptions
Catching specific exceptions makes code to respond to different exception
types differently.
Example:
try:
x = int("str") # This will cause ValueError
#inverse
inv = 1 / x
except ValueError:
print("Not Valid!")
except ZeroDivisionError:
print("Zero has no inverse!")
OUTPUT:
Not Valid!
Catching Multiple Exceptions
We can catch multiple exceptions in a single block if we need to handle
them in the same way or we can separate them if different types of
exceptions require different handling.
Example:
a = ["10", "twenty", 30] # Mixed list of integers and strings
try:
total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to int
except (ValueError, TypeError) as e:
print("Error", e)
except IndexError:
print("Index out of range.")
Raise an Exception
We raise an exception in Python using the raise keyword followed
by an instance of the exception class that we want to trigger. We can
choose from built-in exceptions or define our own custom exceptions
by inheriting from Python's built-in Exception class.
Syntax:
raise ExceptionType("Error message")
Example:
def set(age):
if age < 0:
raise ValueError("Age cannot be negative.")
print(f"Age set to {age}")
try:
set(-5)
except ValueError as e:
print(e)
Output
Age cannot be negative.
Advantages of Exception Handling:
Improved program reliability: By handling exceptions properly, you
can prevent your program from crashing or producing incorrect results
due to unexpected errors or input.
Simplified error handling: Exception handling allows you to separate
error handling code from the main program logic, making it easier to
read and maintain your code.
Cleaner code: With exception handling, you can avoid using complex
conditional statements to check for errors, leading to cleaner and more
readable code.
Easier debugging: When an exception is raised, the Python
interpreter prints a traceback that shows the exact location where the
exception occurred, making it easier to debug your code.
Disadvantages of Exception Handling:
Performance overhead: Exception handling can be slower than using
conditional statements to check for errors, as the interpreter has to
perform additional work to catch and handle the exception.
Increased code complexity: Exception handling can make your code
more complex, especially if you have to handle multiple types of
exceptions or implement complex error handling logic.
Possible security risks: Improperly handled exceptions can
potentially reveal sensitive information or create security vulnerabilities
in your code, so it's important to handle exceptions carefully and avoid
exposing too much information about your program.
Common Exceptions in Python
Exception Name Description
Raised when a division or modulo operation is
ZeroDivisionError performed with zero as the divisor.
Raised when a numerical operation exceeds the
OverflowError maximum limit of a data type.
FloatingPointError Raised when a floating-point operation fails.
IndexError Raised when a sequence subscript is out of range.
Exception Name Description
MemoryError Raised when an operation runs out of memory.
NameError Raised when a local or global name is not found.
Raised when an operation or function is applied to an
TypeError object of inappropriate type.
ImportError Raised when an import statement has issues.
ModuleNotFoundError Raised when a module cannot be found.
Raised when an I/O operation (like reading or writing to
IOError a file) fails.
Raised when a file or directory is requested but cannot
FileNotFoundError be found.
Raised when the user presses Ctrl+C or interrupts the
KeyboardInterrupt program’s execution.
RuntimeError Raised when a general error occurs in the program.
SyntaxError Raised when there is an error in the syntax of the code.
Difference Between Exception and Error
Error: Errors are serious issues that a program should not try to
handle. They are usually problems in the code's logic or configuration
and need to be fixed by the programmer. Examples include syntax
errors and memory errors.
Exception: Exceptions are less severe than errors and can be handled
by the program. They occur due to situations like invalid input, missing
files or network issues.
Command-Line Arguments
Command-line arguments are those which are passed during the calling
of the program along with the calling statement. To achieve this using the
sys module, the sys module provides a variable called [Link]. It's main
purpose are:
It is a list of command-line arguments.
len([Link]) provides the number of command-line arguments.
Example:
import sys
n = len([Link])
print("Total arguments passed:", n)
print("Name of Python script:", [Link][0])
print("Arguments passed:", end=" ")
for i in range(1, n):
print([Link][i], end=" ")
Sum = 0
for i in range(1, n):
Sum += int([Link][i])
print(Sum)
This code sums the command-line arguments passed to the script by
converting each to an integer and adding them up using the sys module.
Python sys Module
The sys module provides access to variables and functions that interact closely
with Python interpreter and runtime environment. It allows developers to
manipulate various aspects of program execution and interpreter itself.
Example:
import sys
print([Link])
Input and Output using sys
The sys module controls program input, output and error streams,
enabling precise data handling beyond standard input and print functions.
1. [Link]:
Reads input directly from the standard input stream and supports reading
multiple lines or redirected input.
import sys
for line in [Link]:
if 'q' == [Link]():
break
print(f'Input : {line}')
print("Exit")
2. [Link]:
Writes output to the standard output stream and allows low-level control
over printed output.
import sys
[Link]('Geeks')
3. [Link]:
Writes messages to the standard error stream and separates error
messages from regular output
import sys
def fun(*args):
print(*args, file=[Link])
fun("Hello World")
Python Modules
Python Module is a file that contains built-in functions, classes, and
variables. There are many Python modules, each with its specific work.
What is Python Module
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also
include runnable code.
Grouping related code into a module makes the code easier to understand
and use. It also makes the code logically organized.
Create a Python Module
To create a Python module,
Example:
create a simple [Link] in which we define two functions, one add and
another subtract.
# A simple module, [Link]
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the
module if the module is present in the search path.
Syntax
import module
Ex:
# importing module [Link]
import calc
print([Link](10, 2))
Python Import From Module
Python's from statement lets you import specific attributes from a module
without importing the module as a whole.
Import Specific Attributes from a Python module
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Import all Names
The * symbol used with the import statement is used to import all the
names from a module to a current namespace.
Syntax:
from module_name import *
# importing sqrt() and factorial from the
# module math
from math import *
# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several
locations. First, it will check for the built-in module, if not found then it
looks for a list of directories defined in the [Link]. Python interpreter
searches for the module in the following manner -
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python then searches
each directory in the shell variable PYTHONPATH. The PYTHONPATH
is an environment variable, consisting of a list of directories.
If that also fails python checks the installation-dependent list of
directories configured at the time Python is installed.
Directories List for Modules
Here, [Link] is a built-in variable within the sys module. It contains a list
of directories that the interpreter will search for the required module.
# importing sys module
import sys
# importing [Link]
print([Link])
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax: Import Module_name as Alias_name
# importing sqrt() and factorial from the
# module math
import math as mt
# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print([Link](16))
print([Link](6))
Python Built-in modules
There are several built-in modules in Python, which you can import
whenever you like.
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print([Link](25))
# using pi function contained in math module
print([Link])
# 2 radians = 114.59 degrees
print([Link](2))
# 60 degrees = 1.04 radians
print([Link](60))
# Sine of 2 radians
print([Link](2))
# Cosine of 0.5 radians
print([Link](0.5))
# Tangent of 0.23 radians
print([Link](0.23))
# 1 * 2 * 3 * 4 = 24
print([Link](4))
# importing built in module random
import random
# printing random integer between 0 and 5
print([Link](0, 5))
# print random floating point number between 0 and 1
print([Link]())
# random number between 0 and 100
print([Link]() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print([Link](List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print([Link]())
# Converts a number of seconds to a date object
print([Link](454554))
What is Python Module
A Python module is a file containing Python definitions and statements. A
module can define functions, classes, and variables. A module can also include
runnable code.
Grouping related code into a module makes the code easier to understand and
use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a file
with .py extension.
Example:
# A simple module, [Link]
def add(x, y):
return (x+y)
def subtract(x, y):
return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to another
module using the import statement in some other Python source file.
When the interpreter encounters an import statement, it imports the module if
the module is present in the search path.
Syntax
import module
Example
# importing sqrt() and factorial from the
# module math
from math import sqrt, factorial
# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Import all Names
The * symbol used with the import statement is used to import all the
names from a module to a current namespace.
Syntax:
from module_name import *
Example
# importing sqrt() and factorial from the
# module math
from math import *
# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for several
locations. First, it will check for the built-in module, if not found then it looks
for a list of directories defined in the [Link]. Python interpreter searches for
the module in the following manner -
First, it searches for the module in the current directory.
If the module isn’t found in the current directory, Python then searches
each directory in the shell variable PYTHONPATH. The PYTHONPATH
is an environment variable, consisting of a list of directories.
If that also fails python checks the installation-dependent list of directories
configured at the time Python is installed.
Directories List for Modules
Here, [Link] is a built-in variable within the sys module. It contains a list of
directories that the interpreter will search for the required module.
# importing sys module
import sys
# importing [Link]
print([Link])
Renaming the Python Module
We can rename the module while importing it using the keyword.
Syntax:
import Module_name as Alias_name
# importing sqrt() and factorial from the
# module math
import math as mt
# if we simply do "import math", then
# [Link](16) and [Link]()
# are required.
print([Link](16))
print([Link](6))
Python Built-in modules
There are several built-in modules in Python, which can import whenever
we like.
# importing built-in module math
import math
# using square root(sqrt) function contained
# in math module
print([Link](25))
# using pi function contained in math module
print([Link])
# 2 radians = 114.59 degrees
print([Link](2))
# 60 degrees = 1.04 radians
print([Link](60))
# Sine of 2 radians
print([Link](2))
# Cosine of 0.5 radians
print([Link](0.5))
# Tangent of 0.23 radians
print([Link](0.23))
# 1 * 2 * 3 * 4 = 24
print([Link](4))
# importing built in module random
import random
# printing random integer between 0 and 5
print([Link](0, 5))
# print random floating point number between 0 and 1
print([Link]())
# random number between 0 and 100
print([Link]() * 100)
List = [1, 4, True, 800, "python", 27, "hello"]
# using choice function in random module for choosing
# a random element from a set such as a list
print([Link](List))
# importing built in module datetime
import datetime
from datetime import date
import time
# Returns the number of seconds since the
# Unix Epoch, January 1st 1970
print([Link]())
# Converts a number of seconds to a date object
print([Link](454554))
Python Packages
Python packages are a way to organize and structure code by grouping related
modules into directories. A package is essentially a folder that contains an
__init__.py file and one or more Python files (modules).
This organization helps manage and reuse code effectively, especially in larger
projects. It also allows functionality to be easily shared and distributed across
different applications.
Packages act like toolboxes, storing and organizing tools for efficient access
and reuse.
Key Components of a Python Package
Module: A single Python file containing reusable code (e.g., [Link]).
Package: A directory containing modules and a special __init__.py file.
Sub-Packages: Packages nested within other packages for deeper
organization.
How to create and access packages in python
1. Create a Directory: Make a directory for your package. This will serve as
the root folder.
2. Add Modules: Add Python files (modules) to the directory, each
representing specific functionality.
3. Include __init__.py: Add an __init__.py file (can be empty) to the
directory to mark it as a package.
4. Add Sub packages (Optional): Create subdirectories with their own
__init__.py files for sub packages.
5. Import Modules: Use dot notation to import, e.g., from
mypackage.module1 import greet.
Steps to create packages
A package can contain one or more relevant modules. Physically,
a package is actually a folder containing one or more module
files.
Create a new folder named D:\MyApp .
Inside MyApp , create a subfolder with the name 'mypackage'.
Create an empty __init__.py file in the mypackage folder.
Using a Python-aware editor like IDLE, create modules
[Link] and [Link] with the following code:
Ex:
[Link]
def SayHello(name):
print("Hello ", name)
[Link]
def sum(x,y):
return x+y
def average(x,y):
return (x+y)/2
def power(x,y):
return x**y
We have created our package called mypackage.
The following is a folder structure:
Importing a Module from a
Package
Now, to test our package, navigate the command prompt to
the MyApp folder and invoke the Python prompt from there.
D:\MyApp>python
Import the functions module from the mypackage package and
call its power() function.
>>> from mypackage import functions
>>> [Link](3,2)
__init__.py
The package folder contains a special file called __init__.py,
which stores the package's content. It serves two purposes:
1. The Python interpreter recognizes a folder as the package if
it contains __init__.py file.
2. __init__.py exposes specified resources from its modules to
be imported.
An empty __init__.py file makes all functions from the 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. You can optionally define functions from
individual modules to be made available.
The __init__.py file is normally kept empty. However, it can also
be used to choose specific functions from modules in the package
folder and make them available for import. Modify __init__.py as
below:
__init__.py
from .functions import average, power
from .greet import SayHello
Create [Link] in the MyApp folder to test mypackage.
from mypackage import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x)
[Link]
from mypackage import power, average, SayHello
SayHello()
x=power(3,2)
print("power(3,2) : ", x)
output:
D:\MyApp>python [Link]
Hello world
power(3,2) : 9
Install a Package Globally
Once a package is created, it can be installed for system-wide use
by running the setup script. The script calls setup() function from
the setuptools module.
Save the following code as [Link] in the parent folder MyApp.
Example: [Link]
from setuptools import setup
setup(name='mypackage',
version='0.1',
description='Testing installation of Package',
url='#',
author='auth',
author_email='author@[Link]',
license='MIT',
packages=['mypackage'],
zip_safe=False)
Now execute the following command to install mypackage using
the pip utility. Ensure that the command prompt is in the parent
folder, in this case D:\MyApp.
D:\MyApp>pip install mypackage
Processing d:\MyApp
Installing collected packages: mypack
Running [Link] install for mypack ... done
Successfully installed mypackage-0.1
Now mypackage is available for system-wide use and can be
imported in any script or interpreter.
D:\>python
>>> import mypackage
>>>[Link](10,20)
15.0
>>>[Link](10,2)
100