Professional Documents
Culture Documents
PP(R18)_U2_NotesRK_23012023
PP(R18)_U2_NotesRK_23012023
NOTES MATERIAL
UNIT2
For
B. TECH (AI&DS)
2nd YEAR – 1st SEM (R18)
Faculty:
B. RAVIKRISHNA
DEPARTMENT OF AI&DS
VIGNAN INSTITUTE OF TECHNOLOGY & SCIENCE
DESHMUKHI
PYTHON PROGRAMMING UNIT–I
UNIT – II Syllabus:
Files, Exceptions and Modules
(Chapters 9, 10,12; Text Book: Chun, Core PP, 2nd Edition (2006))
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, Persistent Storage Modules, Related Modules
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
Index:
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
• Persistent Storage Modules
• Related Modules
Exceptions:
• 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
SN Access Description
mode
1 r It opens the file to read-only mode. The file pointer exists at the
beginning. The file is by default open in this mode if no access mode
is passed.
2 rb It opens the file to read-only in binary format. The file pointer exists
at the beginning of the file.
3 r+ It opens the file to read and write both. The file pointer exists at the
beginning of the file.
4 rb+ It opens the file to read and write both in binary format. The file
pointer exists at the beginning of the file.
5 w It opens the file to write only. It overwrites the file if previously
exists or creates a new one if no file exists with the same name. The
file pointer exists at the beginning of the file.
6 wb It opens the file to write only in binary format. It overwrites the file
if it exists previously or creates a new one if no file exists. The file
pointer exists at the beginning of the file.
7 w+ It opens the file to write and read both. It is different from r+ in the
sense that it overwrites the previous file if one exists whereas r+
doesn't overwrite the previously written file. It creates a new file if
no file exists. The file pointer exists at the beginning of the file.
8 wb+ It opens the file to write and read both in binary format. The file
pointer exists at the beginning of the file.
9 a It opens the file in the append mode. The file pointer exists at the
end of the previously written file if exists any. It creates a new file
if no file exists with the same name.
10 ab It opens the file in the append mode in binary format. The pointer
exists at the end of the previously written file. It creates a new file
in binary format if no file exists with the same name.
11 a+ It opens a file to append and read both. The file pointer remains at
the end of the file if a file exists. It creates a new file if no file exists
with the same name.
12 ab+ It opens a file to append and read both in binary format. The file
pointer remains at the end of the file.
Example:
#Program Program to check the file attributes of a file object.
# Open a file
f = open("file1.txt", "r")
print ("Name of the file: ", f.name)
print ("File is Closed! : ", f.closed)
print ("Opening mode : ", f.mode)
Output:
Name of the file: file1.txt
File is Closed! : False
Opening mode : r
Example:
f = open("file1.txt",'r')
print(f.read(0))
Output:
<nothing outputs>
Example:
print(f.read(2))
Output:
Co
Example:
print(f.read(4))
Output:
nten
Example:
print(f.readline())
Output:
t from <file1.txt>
Example:
s= f.readlines() #till end of file
print(s)
Output:
['to test file read write operations in python\n', 'AI&DS\n', '\n']
Program:
f = open("newfile.txt","w+")
s1 = "File contents for newfile.txt"
f.write(s1)
s2="\nMore content for newfile.txt"
f.write(s2)
s3=input("Enter content from keyboard to file:")
f.write("\n Input from keyboard \n")
f.write(s3)
f.tell()
f.seek(0)
print("newfile.txt contents: \n",f.read())
f.close()
Output:
Enter content from keyboard to file: Entering Input from Keyboard to
file\n AI&DS-Python
newfile.txt contents:
File contents for newfile.txt
More content for newfile.txt
input from keyboard
Entering Input from Keyboard to file
AI&DS-Python
can be added
still morelines can be
added in writelines
ope.exists("nofile.txt")
Output:
True
False
Program:
#Truncate a file using ‘truncate()’
f = open("copyfile.txt","r+")
print(f.read())
f.readable() #tell weather or not a file is readable
f.tell()
f.truncate(100)
f.seek(0)
print(f.read())
f.close()
Output:
Content from <file1.txt>
This is a text document
to test file read write operations in python
AI&
Note: <copyfile.txt truncated to 100 chars>
Program:
f1=open("file1.txt","r")
f2=open("file2.txt","r")
f3=open("file2.txt","r")
f = open("binfile.bin","wb+")
a = [3,4,5]
# Convert the integer elements to a bytearray
bytary = bytearray(a)
# Program to display image file using module Image from PIL module
Program:
from PIL import Image
# open method used to open different extension image file
im = Image.open("img.jpg")
# This method will show image in any image viewer
im.show()
Output:
<you can see the image file displayed>
Command-line Arguments
• Python Command Line Arguments provides a convenient way to accept some
information at the command line while running the program.
• The arguments that are given after the name of the Python script are known as
Command Line Arguments and they are used to pass some information to the
program.
For example:
>>> python script.py arg1 arg2 arg3
sys module - System-specific parameters:
The Python sys module provides access to any command-line arguments via the
sys.argv.
This serves two purposes −
sys.argv is the list of command-line arguments.
len(sys.argv) is the number of command-line arguments.
Here sys.argv[0] is the program ie. script name.
Program:
#Python program to perform addition of two numbers and find factorial of
result, pass two values as command line arguments
import sys
from math import factorial
n=len(sys.argv)
print("No. of Args passed", n)
print("Args are: ", sys.argv)
s=int(sys.argv[1])+int(sys.argv[2])
print("Sum of", sys.argv[1], " and", sys.argv[2]," is: ",s)
# print("Sum : %d"%s)
print("Factorial of sum : ",s,"! =", factorial(s))
Output:
Now open command prompt and follow below specified:
File System:
• Access to your file system occurs mostly through the Python os module. This
module serves as the primary interface to your operating system facilities and
services from Python.
• The os module is actually a front-end to the real module that is loaded, a module
that is clearly operating system dependent.
• This "real" module may be one of the following: posix (Unix-based, i.e., Linux,
MacOS X, *BSD, Solaris, etc.), nt (Win32), mac (old MacOS), dos (DOS), os2 (OS/2),
etc.
• Depending on what your system supports, you may not have access to some of the
attributes, which may be available in other operating system modules.
• In addition to managing processes and the process execution environment, the os
module performs most of the major file system operations that the application
developer may wish to take advantage of.
• These features include removing and renaming files, traversing the directory tree,
and managing file accessibility.
• Table: lists some of the more common file or directory operations available to you
from the os module.
File Execution:
• Whether we want to simply run an operating system command, invoke a binary
executable, or another type of script (perhaps a shell script, Perl, or Tcl/Tk), this
involves executing another file somewhere else on the system. Even running other
Python code may call for starting up another Python interpreter, although that may
not always be the case.
• Python's built-in file object returned by Python's built-in open() function has one
important shortcoming. When opened with 'w' mode, the write() method accepts
only the string object.
• That means, if you have data represented in any non-string form, the object of
either in built-in classes (numbers, dictionary, lists or tuples) or other user-defined
classes, it cannot be written to file directly. Before writing, you need to convert it
in its string representation.
• When simple disk files are no longer acceptable and full relational database
management systems (RDBMSs) are overkill, simple persistent storage fills the gap.
• The majority of the persistent storage modules deals with storing strings of data,
but there are ways to archive Python objects as well.
Shelve:
• Finally, we have a somewhat more complete solution, the shelve module. The shelve
module uses the any dbm module to find a suitable DBM module, then uses cPickle
to perform the pickling process. The shelve module permits concurrent read access
to the database file, but not shared read/write access.
• This is about as close to persistent storage as you will find in the Python standard
library.
Persistent Storage Modules other external extension modules that implement "true" persistent
storage. The diagram in Figure shows the relationship between the pickling modules and the
persistent storage modules, and how the shelve object appears to be the best of both worlds.
Related Modules:
There are plenty of other modules related to files and input/output, all of which work on most
of the major platforms.
Below Table lists some of the file related modules.
Table: Related File Modules
Module(s) Contents
base64 Encoding/decoding of binary strings to/from text strings
binascii Encoding/decoding of binary and ASCII-encoded binary strings
bz2 Allows access to BZ2 compressed files
csv Allows access to comma-separated value files
filecmp Compares directories and files
fileinput Iterates over lines of multiple input text files
Exceptions in Python:
Before knowing about Exception, let’s understand about errors in programming.
What’s an Error?
▪ Errors are the problems in a program due to which the program will stop the
execution. On the other hand, exceptions are raised when some internal events occur
which changes the normal flow of the program.
▪ Two types of Error occur in python.
▪ Syntax errors
▪ Logical errors (Exceptions)
▪ Syntax Errors:
Syntax errors, also known as parsing errors, are perhaps the most common kind
of complaint you get while you are still learning Python:
• Exception handling allows you to separate error-handling code from normal code.
• As with code comments, exceptions helps you to remind yourself of what the
program expects.
• It clarifies the code and enhances readability.
• Allows you to stimulate consequences as the error-handling takes place at one
place and in one manner.
• An exception is a convenient method for handling error messages.
• Raising an exception helps you to break the current code execution and returns
the exception back to expectation until it is handled.
• Processing exceptions for components which can’t handle them directly.
Syntax:
try:
• The try block lets you test a block of code for errors.
except:
• If the try block encounters an exception, except block will handle it.
else:
• If there is no exception, else code block will be executed.
finally:
The finally block lets you execute code,
regardless of the result of the try- and except
blocks.
Example:
print(x) #error if x not defined.
Output:
Traceback (most recent call last):
Cell In[25], line 1
print(x) #error if x not defined.
NameError: name 'x' is not defined
Example:
#Exception when x is not defined
try:
print("x is defined and x= ",x)
except:
print("exception raised Something went wrong")
Output:
exception raised Something went wrong
Example:
#Named Exception when x is not defined
try:
print("x is defined and x= ",x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
Output:
Variable x is not defined
Example:
# Exception with else: else executes if try didn't raise exception
try:
x=3
print("x is defined and x= ",x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
Output:
x is defined and x= 3
Program:
#Exception with something else: x is defined, but raising another exception
x = 4
try:
print("x is defined and x= ", x)
print("x/0", x/0)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
Output:
x is defined and x= 4
Something else went wrong
Program:
#finally block & out of try & exception blocks
try:
print("x/0",x/0)
print("x is defined and x= ",x)
except NameError:
print("Variable x is not defined")
except:
print("Something else went wrong")
else:
print("Nothing went wrong")
finally:
print("finally executes 'finally block' ")
print("Out of try block")
Output:
Something else went wrong
finally executes 'finally block'
Out of try block
Raise an exception:
• As a Python developer you can choose to throw an exception if a condition occurs.
• To throw (or raise) an exception, use the raise keyword.
• The raise keyword is used to raise an exception.
• You can define what kind of error to raise, and the text to print to the user.
Example:
Python code to show how to raise an exception in Python
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
Ouput:
TypeError: Only integers are allowed
Example:
#raise and exception under condition, with list
l = [1,2,3,4,5]
ln=len(l)
if ln > 3:
raise Exception ("Length of the given list must be less than or
equal to 3 but is", ln)
Assertion Error:
▪ The assert keyword lets you test if a condition in your code returns True, if not,
the program will raise an AssertionError.
Example:
n=16
assert (n>0), "Needs a +ve Number"
n**(1/2)
Output:
4.0
Example:
n=-16
assert (n>0), "Needs a +ve Number"
n**(1/2)
Output:
Needs a +ve Number
▪ To create a custom Exception, we must create a new class. This exception class has to be
derived, directly or indirectly, from the built-in Exception class.
▪ Usually, the defined exception name ends with the word Error which follows the standard
naming convention; however, it is not compulsory to do so.
Example:
class MyError(Exception):
print("Calling Successful")
Output:
Calling Successful
Traceback (most recent call last):
Example:
# Context Management - The with Statement Approach
with open("file1.txt", mode="a+") as f:
f.write("\nMore Contents!")
print("file contents added!")
Output:
file contents added!
Note: Though in the above code, we didn’t close the file, as we used context
using ‘with’, file closed once write operation is done. Hence you find the below
error.
Example:
f.tell() #Check the error
f.seek(0) #Check the error
Output:
ValueError: I/O operation on closed file.
ValueError: I/O operation on closed file.
Modules In Python:
• Modules in Python are simply Python files with the .py extension that can contain a
set of functions, classes, or variables.
• In simple Python module is a file containing Python definitions and statements.
• Grouping related code into a module makes the code easier to understand and use.
• It also makes the code logically organized. We import those module/s to the required
program.
• An example_module.py file is a module we will create and whose name is
example_module.
• Rather than duplicating their definitions into several applications, we may define
our most frequently used functions in a separate module and then import the
complete module.
Let's construct a module. Save the file as example_module.py after entering the following.
First create a python file <file.py> and save, to use it as module.
#Program to create ‘mymodule.py’
#<mymodule.py>
#Creating a module with name ‘mymodule.py’.
def message(name):
print ("Imported from "+name)
d1 = {2:"Two", 'b':22, 3.4:"Three"}
def add(a,b):
return a*b
Note: No need to run the program
Importing mymodule.py in current file:
Program: <modexmple.py>
import mymodule
mymodule.message("mymodule.py")
Output:
Imported from mymodule.py
Output:
22
Three
the module's namespace is created. This namespace contains all the variables,
functions, and classes defined in the module.
• When you import a module in Python, the contents of the module are added to a
new namespace, which is created specifically for that module. The namespace is
then made available to the rest of the program through the module's name.
• For example, if you have a module named "mymodule" and you import it using the
statement "import mymodule", you can access the contents of the module by
prefixing the names with the module name and a dot (.) like
mymodule.function_name or mymodule.class_name.
Here are a few examples to help understand how namespaces work in Python:
Using the import statement:
Example:
<mymodule.py>
x = 5
def print_x():
print(x)
# main.py
import mymodule
print(mymodule.x) # prints 5
mymodule.print_x() # prints 5
Here are a few examples to help understand how namespaces work in Python:
Using the import statement:
Example:
# mymodule.py
x = 5
def print_x():
print(x)
# main.py
import mymodule
print(mymodule.x) # prints 5
mymodule.print_x() # prints 5
Here, mymodule is a separate namespace with the variable x and function print_x() in it.
To access them, we need to use the namespace mymodule before the variable or function
name.
Example:
Using the 'from' statement:
<mymodule.py>
x = 5
def print_x():
print(x)
Copy code
# main.py
from mymodule import x, print_x
print(x) # prints 5
print_x() # prints 5
Here, we imported x and print_x() from the mymodule namespace into the current
namespace, so we can use them directly without referencing the namespace.
Related Modules:
The following are auxiliary modules that you may use when dealing with the import of Python
modules. Of these listed below, modulefinder, pkgutil, and zipimport are new as of Python 2.3,
and the distutils package was introduced back in version 2.0
• imp: this module gives you access to some lower-level importer functionality.
• Modulefinder: this is a module that lets you find all the modules that are used by a Python
script. You can either use the ModuleFinder class or just run it as a script giving it the
filename of a (nother) Python module with which to do module analysis on.
• pkgutil this module gives those putting together Python packages for distribution a way to
place package files in various places yet maintain the abstraction of a single "package" file
hierarchy. It uses *.pkg files in a manner similar to the way the site module uses *.pth files to
help define the package path.
• site using this module along with *.pth files gives you the ability to specify the order in which
packages are added to your Python path, i.e., sys.path, PYTHONPATH. You do not have to
import it xplicitly as the importer already uses it by defaultyou need to use the -S switch when
starting up Python to turn it off. Also, you can perform further arbitrary site-specific
customizations by adding a sitecustomize module whose import is attempted after the path
manipulations have been completed.
• zipimport this module allows you to be able to import Python modules that are archived in
ZIP files. Note that the functionality in this file is "automagically" called by the importer so
there is no need to import this file for use in any application. We mention it here solely as a
reference.
• distutils this package provides support for building, installing, and distributing Python
modules and packages. It also aids in building Python extensions written in C/C++.
Packages in Python:
• A Python package is a directory that contains zero or more Python modules.
• A Python package can contain sub-packages, which are also directories containing
modules.
• Each package always contains a special file named __init__.py.
• A package is a container that contains various functions to perform specific tasks.
• For example, the math package includes the sqrt() function to perform the square root of
a number.
• While working on big projects, we have to deal with a large amount of code, and writing
everything together in the same file will make our code look messy. Instead, we can
separate our code into multiple files by keeping the related code together in packages.
• The sys.modules variable consists of a dictionary of modules that the interpreter has
currently loaded (in full and successfully) into the interpreter. The module names are the
keys, and the location from which they were imported are the values.
• For example, in Windows, the sys.modules variable contains a large number of loaded
modules, so we will shorten the list by requesting only the module names. This is
accomplished by using the dictionary's keys() method: