0% found this document useful (0 votes)
19 views

Unit-IV

mmmmmmmm

Uploaded by

Brazil Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Unit-IV

mmmmmmmm

Uploaded by

Brazil Account
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Python File:

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

Since Random Access Memory (RAM) is volatile (which loses its data when the computer is
turned off), we use files for future use of the data by permanently storing them.

When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.

Hence, in Python, a file operation takes place in the following order:

• Open a file
• Read or write (perform operation)
• Close the file

Opening and Closing Files:

Until now, you have been reading and writing to the standard input and output. Now, we will
see how to use actual data files.

Python provides basic functions and methods necessary to manipulate files by default. You can
do most of the file manipulation using a file object.

The open Function:

Before you can read or write a file, you have to open it using Python's built-in open() function.
This function creates a file object, which would be utilized to call other support methods
associated with it.

Syntax:

file_object=open(file_name, access_mode, buffering)

Here are parameter details −


• file_name − The file_name argument is a string value that contains the name of the
file that you want to access.
• 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 optional parameter and the default file access mode is read (r).
• 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
behaviour).
Here is a list of the different modes of opening a file −

Sr.No. Modes & Description

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

The file Object Attributes

Once a file is opened and you have one file object, you can get various information related to
that file. Here is a list of all attributes related to file object −

Sr.No. Attribute & Description

1 file.closed
Returns true if file is closed, false otherwise.

2 file.mode
Returns access mode with which file was opened.

3 file.name
Returns name of the file.

4 file.softspace
Returns false if space explicitly required with print, true otherwise.
Example: Assume we have the following file, located in the same folder as Python:

demofile.txt

Hello! Welcome to demofile.txt


This file is for testing purposes.
Good Luck!
Example:

file = open("demofile.txt", "r")


print ("Name of the file: ", file.name)
print ("Closed or not: ", file.closed)
print ("Opening mode: ", file.mode)

Output:

Name of the file: demofile.txt


Closed or not: False
Opening mode: r

The close() Method:


The close() method 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() method to close a file.

Syntax
fileObject.close()

Example:

file = open("demofile.txt", "r")


print ("Name of the file: ", file.name)
file.close()
Output:

Name of the file: demofile.txt


Reading and Writing Files:
The file object provides a set of access methods to make our lives easier. We would see how
to use read() and write() methods to read and write files.

The write() Method:


The write() method writes any string to an open file. It is important to note that Python strings
can have binary data and not just text. The write() method does not add a newline character
('\n') to the end of the string −
Syntax
fileObject.write(string)
Here, passed parameter is the content to be written into the opened file.

Example: Open the file "demofile.txt" and append content to the file:
f = open("demofile.txt", "a")

f.write("Now the file has more content!")

f.close()

#open and read the file after the appending:

f = open("demofile.txt", "r")

print(f.read())

Output:

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!Now the file has more content!

The read() Method


The read() method reads a string from an open file. It is important to note that Python strings
can have binary data. apart from text data.
Syntax
fileObject.read([count])
Here, passed parameter is the number of bytes to be read from the opened file. This method
starts reading from the beginning of the file and if count is missing, then it tries to read as
much as possible, maybe until the end of file.
f = open("demofile.txt", "r")

print(f.read())
Output:

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!

Read Only Parts of the File: By default the read() method returns the whole text, but you can
also specify how many characters you want to return:

Example: Return the 5 first characters of the file:

f = open("demofile.txt", "r")

print(f.read(5))

Output:

Hello

Read Lines: You can return one line by using the readline() method:

Example: Read one line of the file:

f = open("demofile.txt", "r")

print(f.readline())

Output:

Hello! Welcome to demofile.txt

By looping through the lines of the file, you can read the whole file, line by line:

Example: Loop through the file line by line:

f = open("demofile.txt", "r")

for x in f:

print(x)

Output:

Hello! Welcome to demofile.txt

This file is for testing purposes.

Good Luck!
Python File Methods:
A file object is created using open function and here is a list of functions which can be called
on this object −

Sr.No. Methods with Description

1 file.close()
Close the file. A closed file cannot be read or written any more.

2 file.flush()
Flush the internal buffer, like stdio's fflush. This may be a no-op on some file-like
objects.

3 file.fileno()
Returns the integer file descriptor that is used by the underlying implementation to
request I/O operations from the operating system.

4 file.isatty()
Returns True if the file is connected to a tty(-like) device, else False.

5 file.next()
Returns the next line from the file each time it is being called.

6 file.read([size])
Reads at most size bytes from the file (less if the read hits EOF before obtaining size
bytes).

7 file.readline([size])
Reads one entire line from the file. A trailing newline character is kept in the string.

8 file.readlines([sizehint])
Reads until EOF using readline() and return a list containing the lines. 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.

9 file.seek(offset[, whence])
Sets the file's current position
10 file.tell()
Returns the file's current position

11 file.truncate([size])
Truncates the file's size. If the optional size argument is present, the file is truncated
to (at most) that size.

12 file.write(str)
Writes a string to the file. There is no return value.

13 file.writelines(sequence)
Writes a sequence of strings to the file. The sequence can be any iterable object
producing strings, typically a list of strings.

File Positions

The tell() method tells you the current position within the file; in other words, the next read or
write will occur at that many bytes from the beginning of the file.

The seek(offset[, from]) method changes the current file position. The offset argument
indicates the number of bytes to be moved. The from argument specifies the reference position
from where the bytes are to be moved.

If from is set to 0, it means use the beginning of the file as the reference position and 1 means
use the current position as the reference position and if it is set to 2 then the end of the file
would be taken as the reference position.

Example:

file = open("demofile.txt", "r+")


str = file.read(14)
print("Read String is : ", str)

# Check current position


position = file.tell()
print(“Current file position : “, position)

# Reposition pointer at the beginning once again


position = file.seek(0, 0);
str = file.read(14)
print(“Again read String is : “, str)
#Close opend file
file.close()
Output:
Read String is : Hello! Welcome
Current file position : 14
Again read String is : Hello! Welcome

Renaming and Deleting Files:


Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
To use this module, you need to import it first and then you can call any related functions.

The rename() Method:


The rename() method takes two arguments, the current filename and the new filename.
Syntax:
os.rename(current_file_name, new_file_name)
Example:

import os

# Rename a file from test1.txt to test2.txt

os.rename( "test1.txt", "test2.txt" )

The remove() Method:

You can use the remove() method to delete files by supplying the name of the file to be deleted
as the argument.

Syntax

os.remove(file_name)
Example: Remove the file "demofile.txt":

import os

os.remove("demofile.txt")

Check if File exist: To avoid getting an error, you might want to check if the file exists before
you try to delete it:

Example: Check if file exists, then delete it:

import os

if os.path.exists("demofile.txt"):

os.remove("demofile.txt")

else:

print("The file does not exist")

Directories in Python:

All files are contained within various directories, and Python has no problem handling these
too. The os module has several methods that help you create, remove, and change directories.

The mkdir() Method:

You can use the mkdir() method of the os module to create directories in the current directory.
You need to supply an argument to this method which contains the name of the directory to be
created.

Syntax:

os.mkdir("newdir")

Example:

Following is the example to create a directory test in the current directory −

import os

# Create a directory "test"

os.mkdir("test")

The chdir() Method:

You can use the chdir() method to change the current directory. The chdir() method takes an
argument, which is the name of the directory that you want to make the current directory.
Syntax:

os.chdir("newdir")

Example:

Following is the example to go into "/home/newdir" directory −

import os

# Changing a directory to "/home/newdir"

os.chdir("/home/newdir")

The getcwd() Method:

The getcwd() method displays the current working directory.

Syntax:

os.getcwd()

Example:

Following is the example to give current directory −

import os

# This would give location of the current directory

os.getcwd()

The rmdir() Method:

The rmdir() method deletes the directory, which is passed as an argument in the method.

Before removing a directory, all the contents in it should be removed.

Syntax:

os.rmdir('dirname')

Example:

Following is the example to remove "/tmp/test" directory. It is required to give fully qualified
name of the directory, otherwise it would search for that directory in the current directory.

import os

# This would remove "/tmp/test" directory.

os.rmdir( "/tmp/test" )
Command Line Arguments in Python:

The arguments that are given after the name of the program in the command line shell of the
operating system are known as Command Line Arguments. Python provides various ways of
dealing with these types of arguments.

The three most common are:

1. Using sys.argv
2. Using getopt module
3. Using argparse module

1. Using sys.argv

The sys module provides functions and variables used to manipulate different parts of the
Python runtime environment. This module provides access to some variables used or
maintained by the interpreter and to functions that interact strongly with the interpreter.

One such variable is sys.argv which is a simple list structure. It’s main purpose are:

• It is a list of command line arguments.


• len(sys.argv) provides the number of command line arguments.
• sys.argv[0] is the name of the current Python script.

Example: Let’s suppose there is a Python script for adding two numbers and the numbers are
passed as command-line arguments.

import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)

# Arguments passed
print("\nName of Python script:", sys.argv[0])

print("\nArguments passed:", end = " ")


for i in range(1, n):
print(sys.argv[i], end = " ")

# Addition of numbers
Sum = 0
# Using argparse module
for i in range(1, n):
Sum += int(sys.argv[i])
print("\n\nResult:", Sum)
Output:
C:\Users\MURALI\Desktop\Python\Lab>python cla.py 20 30
Total arguments passed: 3
Name of Python script: cla.py
Arguments passed: 20 30
Result: 50
2. Using getopt module:
Python getopt module is similar to the getopt() function of C. Unlike sys module getopt module
extends the separation of the input string by parameter validation. It allows both short, and long
options including a value assignment. However, this module requires the use of the sys module
to process input data properly. To use getopt module, it is required to remove the first element
from the list of command-line arguments.
Syntax:
getopt.getopt(args, options, [long_options])
Parameters:
args: List of arguments to be passed.
options: String of option letters that the script want to recognize. Options that require
an argument should be followed by a colon (:).
long_options: List of string with the name of long options. Options that require
arguments should be followed by an equal sign (=).
Return Type: Returns value consisting of two elements: the first is a list of (option,
value) pairs. The second is the list of program arguments left after the option list was
stripped.
Example:
import getopt, sys
# Remove 1st argument from the
# list of command line arguments
argumentList = sys.argv[1:]
# Options
options = "hmo:"

# Long options
long_options = ["Help", "My_file", "Output ="]

try:
# Parsing argument
arguments, values = getopt.getopt(argumentList, options, long_options)

# checking each argument


for currentArgument, currentValue in arguments:

if currentArgument in ("-h", "--Help"):


print ("Displaying Help")

elif currentArgument in ("-m", "--My_file"):


print ("Displaying file_name:", sys.argv[0])

elif currentArgument in ("-o", "--Output"):


print (("Enabling special output mode (% s)") % (currentValue))

except getopt.error as err:


# output error, and return with an error code
print (str(err))
3. Using argparse module
Using argparse module is a better option than the above two options as it provides a lot of
options such as positional arguments, default value for arguments, help message, specifying
data type of argument etc.
Note: As a default optional argument, it includes -h, along with its long version –help.
Example 1: Basic use of argparse module.
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
parser.parse_args()
Output:
C:\Users\MURALI\Desktop\Python\Lab>python aparse.py -h
usage: getopt.py [-h]
optional arguments:
-h, --help show this help message and exit

Example 2: Adding description to the help message.


import argparse
msg = "Adding description"
# Initialize parser
parser = argparse.ArgumentParser(description = msg)
parser.parse_args()
Output:
C:\Users\MURALI\Desktop\Python\Lab>python aparse.py -h
usage: aparse.py [-h]
Adding description
optional arguments:
-h, --help show this help message and exit
Example 3: Defining optional value
import argparse
# Initialize parser
parser = argparse.ArgumentParser()
# Adding optional argument
parser.add_argument("-o", "--Output", help = "Show Output")
# Read arguments from command line
args = parser.parse_args()
if args.Output:
print("Displaying Output as: % s" % args.Output)
Output:
C:\Users\MURALI\Desktop\Python\Lab>python aparse.py -o Red
Displaying Output as: Red
C:\Users\MURALI\Desktop\Python\Lab>python aparse.py -o
usage: aparse.py [-h] [-o OUTPUT]
aparse.py: error: argument -o/--Output: expected one argument

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.

You should never import those modules directly. Just import os and the appropriate module
will be loaded, keeping all the underlying work hidden from sight. 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.

Lists some of the more common file or directory operations available to you from the os
module.
Function Description

File Processing:

mkfifo()/mknod() Create named pipe/create file system node

remove()/unlink() Delete file

rename()/renames() Rename file

symlink() Create symbolic link

utime() Update timestamp

tmpfile() Create and open ('w+b') new temporary file

walk() Generate filenames in a directory tree

Directories/Folders:

chdir()/fchdir() Change working directory/via a file descriptor

chroot() Change root directory of current process

listdir() List files in directory

getcwd()/getcwdu() Return current working directory/same but in Unicode

mkdir()/makedirs() Create directory(ies)

rmdir()/removedirs() Remove directory(ies)

Access/Permissions:

access() Verify permission modes

chmod() Change permission modes

chown()/lchown() Change owner and group ID/same, but do not follow links

umask() Set default permission modes


Persistent Storage Modules:
In many of the exercises, user input is required. After many iterations, it may be somewhat
frustrating being required to enter the same data repeatedly. The same may occur if you are
entering a significant amount of data for use in the future. This is where it becomes useful to
have persistent storage, or a way to archive your data so that you may access them at a later
time instead of having to re-enter all of that information. 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.

pickle module:

• Python objects can be serialized into binary form and deserialized back to Python
objects using the methods and classes available from the Python module pickle.
• The process of converting a Python object into binary form is called Pickling.
• The process of converting the binary stream back to a Python object is called
Unpickling.
• Pickled objects can be stored in a disk file and unpickled back as objects.
• The Python module pickle provides the methods, classes, constants and exceptions to
be used during the pickling process.
• While the dump() variants pickle the Python object hierarchies the load() variants
unpickle the bytes back into Python object hierarchies.

Pickle example:

import pickle
data = ['one', 2, [3, 4, 5]]
with open('data.dat', 'wb') as f:
pickle.dump(data, f)
Unpickle example:

import pickle
objdump = None
with open('data.dat', rb') as f:
# Stores the now deserialized information into objdump
objdump = pickle.load(f)

shelve module:

In Python shelve you access the keys randomly. In order to access the keys randomly in
python shelve we use open() function. This function works a lot like the file open() function
in File handling.

Syntax:

shelve.open(filename, flag='c' , writeback=True)

In Order to access the keys randomly in shelve in Python, we have to take three steps:

1. Storing Python shelve data


2. Retrieving Python shelve data
3. Updating Python shelve data

1. Storing Python shelve data:

In order to store python shelve data, we have to create a file with full of datasets and open
them with an open() function this function open a file which we have created.

Example:

# At first, we have to import the 'Shelve' module.

import shelve

# In this step, we create a shelf file.

shfile = shelve.open("shelf_file")

# we create a data object which in this case is a book_list.

booklist =['bared to you', 'The fault in our stars', 'The boy who never let her go']

# we are assigning a dictionary key to the list

# which we will want to retrieve

shfile['book_list']= booklist
# now, we simply close the shelf file.

shfile.close()

2. Retrieving Python shelve data:

After storing a shelve data, we have to retrieve some data from a file in order to do that we
use index operator [] as we do in lists and in many other data types.

Example:

# At first, we import the 'Shelve' module.

import shelve

# In this step, we create a shelf file.

var = shelve.open("shelf_file")

# Now, this 'var' variable points to all the

# data objects in the file 'shelf_file'.

print(var['book_list'])

# now, we simply close the file 'shelf_file'.

var.close()

3. Updating Python shelve data:

In order to update a python shelve data, we use append() function or we can easily update as
we do in lists and in other data types. In order to make our changes permanent we use sync()
function.

Example:

# At first, we have to import the 'Shelve' module.

import shelve

# In this step, we create a shelf file.

var = shelve.open("shelf_file", writeback = True)

# inputting total values we want to add

# to the already existing list in shelf_file.

val1 = int(input("Enter the number of values "))


for x in range(val1):

val = input("\n Enter the value\t")

var['book_list'].append(val)

# Now, this 'var' variable will help in printing

# the data objects in the file 'shelf_file'.

print(var['book_list'])

# to make our changes permanent, we use

# synchronize function.

var.sync()

# now, we simply close the file 'shelf_file'.

var.close()
Exceptions:
• An exception can be defined as an unusual condition in a program resulting in the
interruption in the flow of the program.
• Whenever an exception occurs, the program stops the execution, and thus the further
code is not executed.
• An exception is a Python object that represents an error
• Python provides a way to handle the exception so that the code can be executed
without any interruption.
• If we do not handle the exception, the interpreter doesn't execute all the code that
exists after the exception.
• Python has many built-in exceptions that enable our program to run without
interruption and give the output.

Common Exceptions:

• Python provides the number of built-in exceptions, but here we are describing the
common standard exceptions.
• A list of common exceptions that can be thrown from a standard Python program is
given below.

1. ZeroDivisionError: Occurs when a number is divided by zero.


2. NameError: It occurs when a name is not found. It may be local or global.
3. IndentationError: If incorrect indentation is given.
4. IOError: It occurs when Input Output operation fails.
5. EOFError: It occurs when the end of the file is reached, and yet operations are being
performed.

Without handling Exceptions:

a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d" %c)
#other code:
print("Hi I am other part of the program")

Output:

Enter a:10
Enter b:0
Traceback (most recent call last):
File "exception-test.py", line 3, in <module>
c = a/b;
ZeroDivisionError: division by zero
Detecting and Handling Exceptions:

The try-except statement:

• If the Python program contains suspicious code that may throw the exception, we must place that
code in the try block.
• The try block must be followed with the except statement, which contains a block of code that
will be executed if there is some exception in the try block.

Syntax:
try:
#block of code
except Exception1:
#block of code
except Exception2:
#block of code
#other code

Program:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
except:
print("Can't divide with zero")

Output:

Enter a:10
Enter b:0
Can't divide with zero

• We can also use the else statement with the try-except statement in which, we can place the code
which will be executed in the scenario if no exception occurs in the try block.

Syntax:
try:
#block of code
except Exception1:
#block of code
else:
#this code executes if no except block is executed

Program:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using Exception with except statement. If we print(Exception) it will return excepti
on class
except Exception:
print(“can’t divide by zero”)
print(Exception)
else:
print(“Hi I am else block”)
Output:

Enter a:10
Enter b:0
can’t divide by zero
<class ‘Exception’>

The except statement with no exception:

Python provides the flexibility not to specify the name of exception with the exception statement.
Program:

try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
print("can't divide by zero")
else:
print("Hi I am else block")

The except statement using with exception variable:

• We can use the exception variable with the except statement.


• It is used by using the as keyword.
• This object will return the cause of the exception.

Program:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
# Using exception object with the except statement
except Exception as e:
print("can't divide by zero")
print(e)
else:

print("Hi I am else block")

Output:
Enter a:10
Enter b:0
can't divide by zero
division by zero
Points to remember:

1. Python facilitates us to not specify the exception with the except statement.
2. We can declare multiple exceptions in the except statement since the try block may
contain the statements which throw the different type of exceptions.
3. We can also specify an else block along with the try-except statement, which will be
executed if no exception is raised in the try block.
4. The statements that don't throw the exception should be placed inside the else block.

Program:

try:
#this will throw an exception if the file doesn't exist.
fileptr = open("file.txt","r")
except IOError:
print("File not found")
else:
print("The file opened successfully")
fileptr.close()

Output:

File not found

Declaring Multiple Exceptions:

• The Python allows us to declare the multiple exceptions with the except clause.
• Declaring multiple exceptions is useful in the cases where a try block throws multiple exceptions.

Syntax:
try:
#block of code

except (<Exception 1>,<Exception 2>,<Exception 3>,...<Exception n>)


#block of code

else:
#block of code

Program:
try:
a=10/0
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")

Output:
Arithmetic Exception
The try...finally block:

• Python provides the optional finally statement, which is used with the try statement.
• It is executed no matter what exception occurs and used to release the external resource.
• The finally block provides a guarantee of the execution.

Syntax:
try:
# block of code
# this may throw an exception
finally:
# block of code
# this will always be executed

Program:
try:
fileptr = open("file2.txt","r")
try:
fileptr.write("Hi I am good")
finally:
fileptr.close()
print("file closed")
except:
print("Error")

Output:
file closed
Error

Raising exceptions:
• An exception can be raised forcefully by using the raise clause in Python.
• It is useful in that scenario where we need to raise an exception to stop the execution of the
program.

Syntax:
raise Exception_class,<value>

Program:
try:
age = int(input("Enter the age:"))
if(age<18):
raise ValueError
else:
print("the age is valid")
except ValueError:
print("The age is not valid")

Output:
Enter the age:17
The age is not valid
Program:
try:
num = int(input("Enter a positive integer: "))
if(num <= 0):
# we can pass the message in the raise statement
raise ValueError("That is a negative number")
except ValueError as e:
print(e)

Output:
Enter a positive integer: -5
That is a negative number

Program:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
print("The value of b can't be 0")

Output:
Enter a:10
Enter b:0
The value of b can't be 0

Assertions:

• Assertions are statements that assert or state a fact confidently in your program.
• For example, while writing a division function, you're confident the divisor shouldn't
be zero, you assert divisor is not equal to zero.
• Assertions are simply boolean expressions that check if the conditions return true or
not.
• If it is true, the program does nothing and moves to the next line of code. However, if
it's false, the program stops and throws an error.
• It is also a debugging tool as it halts the program as soon as an error occurs and displays
it.
Syntax:
assert <condition>,<error message>
Program:
def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)

mark1 = []
print("Average of mark1:",avg(mark1))
Output:
AssertionError

Program: With error message


def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))
Output:
Average of mark2: 78.0
AssertionError: List is empty.

Standard Exceptions:
Here is a list all the standard Exceptions available in Python.
Sr.No. Exception Name & Description
Exception
1
Base class for all exceptions
StopIteration
2
Raised when the next() method of an iterator does not point to any object.
SystemExit
3
Raised by the sys.exit() function.
StandardError
4
Base class for all built-in exceptions except StopIteration and SystemExit.
ArithmeticError
5
Base class for all errors that occur for numeric calculation.
OverflowError
6
Raised when a calculation exceeds maximum limit for a numeric type.
FloatingPointError
7
Raised when a floating point calculation fails.
ZeroDivisionError
8
Raised when division or modulo by zero takes place for all numeric types.
AssertionError
9
Raised in case of failure of the Assert statement.
AttributeError
10
Raised in case of failure of attribute reference or assignment.
EOFError
11
Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.
ImportError
12
Raised when an import statement fails.
KeyboardInterrupt
13
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
LookupError
14
Base class for all lookup errors.
IndexError
15
Raised when an index is not found in a sequence.
KeyError
16
Raised when the specified key is not found in the dictionary.
NameError
17
Raised when an identifier is not found in the local or global namespace.
UnboundLocalError
18
Raised when trying to access a local variable in a function or method but no
value has been assigned to it.
EnvironmentError
19
Base class for all exceptions that occur outside the Python environment.
IOError
20
Raised when an input/ output operation fails, such as the print statement or the
open() function when trying to open a file that does not exist.
OSError
21
Raised for operating system-related errors.
SyntaxError
22
Raised when there is an error in Python syntax.
IndentationError
23
Raised when indentation is not specified properly.
SystemError
24
Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.
SystemExit
25
Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.
TypeError
26
Raised when an operation or function is attempted that is invalid for the
specified data type.
ValueError
27
Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.
RuntimeError
28
Raised when a generated error does not fall into any category.
Modules:
• A module allows you to logically organize your Python code.
• Grouping related code into a module makes the code easier to understand and use.
• A module is a Python object with arbitrarily named attributes that you can bind and
reference.
• A module is a file consisting of Python code.
• A module can define functions, classes and variables.
• A module can also include runnable code.
• To use the functionality of one module into another, we must have to import the
specific module.

Modules and Files:


Example: create a simple module
arop.py

def add(x, y):


return (x+y)

def subtract(x, y):


return (x-y)

# importing module calc.py


import arop

print(calc.add(10, 2))

Output:
12

Namespaces:
• A namespace is a system that has a unique name for each and every object in Python.
• An object might be a variable or a method.
• Python itself maintains a namespace in the form of a Python dictionary.
• The Python interpreter understands what exact method or variable is trying to point
to in the code, depending upon the namespace.
• Its Name (which means name, a unique identifier) + Space (which talks something
related to scope).

Types of Namespaces:
• When Python interpreter runs solely without any user-defined modules, methods,
classes, etc. Some functions like print(), id() are always present, these are built-in
namespaces.
• When a user creates a module, a global namespace gets created, later the creation of
local functions creates the local namespace.
• The built-in namespace encompasses the global namespace and the global
namespace encompasses the local namespace.

Example:
var1 = 5
def some_func():

# var2 is in the local namespace


var2 = 6
def some_inner_func():

# var3 is in the nested local


# Namespace
var3 = 7

• The same object name can be present in multiple namespaces as isolation between the
same name is maintained by their namespace
Importing Modules:

• Import in python is similar to #include header_file in C/C++.


• Python modules can get access to code from another module by importing the
file/function using import.

Syntax:
import module_name

• When the import is used, it searches for the module initially in the local scope by
calling __import__() function.
• The value returned by the function is then reflected in the output of the initial code.

Example:

import math
print(math.pi)

Output:
3.141592653589793

Importing Module Attributes:

Python’s from statement lets you import specific attributes from a module without importing
the module as a whole.

Syntax 1:
from math import pi

Example:
import math
print(pi)

Output:
3.141592653589793

In the above code module, math is not imported, rather just pi has been imported as a
variable.

Syntax 2:

from module_name import *

All the functions and constants can be imported using *.


Example:
from math import *
print(pi)
print(factorial(6))

Output:
3.141592653589793
720

As said above import uses __import__() to search for the module, and if not found, it would
raise ImportError

Example:
import mathematics
print(mathematics.pi)

Output:
ImportError: No module named 'mathematics'

Module Built-in Functions:

Example:

# importing built-in module math


import math

# using square root(sqrt) function contained


# in math module
print(math.sqrt(25))

# using pi function contained in math module


print(math.pi)

# 2 radians = 114.59 degrees


print(math.degrees(2))

# 60 degrees = 1.04 radians


print(math.radians(60))

# Sine of 2 radians
print(math.sin(2))

# Cosine of 0.5 radians


print(math.cos(0.5))

# Tangent of 0.23 radians


print(math.tan(0.23))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))

# importing built in module random


import random

# printing random integer between 0 and 5


print(random.randint(0, 5))

# print random floating point number between 0 and 1


print(random.random())

# random number between 0 and 100


print(random.random() * 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(random.choice(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(time.time())

# Converts a number of seconds to a date object


print(date.fromtimestamp(454554))

Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
1970-01-06

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy