0% found this document useful (0 votes)
10 views19 pages

Python Unit - IV

This document covers error handling in Python, detailing the types of errors (syntax errors and exceptions) and common exceptions encountered in programming. It explains how to handle exceptions using try-except blocks, the use of else and finally clauses, and how to raise exceptions. Additionally, it discusses data streams, file handling, and the open function with various access modes for file operations.

Uploaded by

Aathi
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)
10 views19 pages

Python Unit - IV

This document covers error handling in Python, detailing the types of errors (syntax errors and exceptions) and common exceptions encountered in programming. It explains how to handle exceptions using try-except blocks, the use of else and finally clauses, and how to raise exceptions. Additionally, it discusses data streams, file handling, and the open function with various access modes for file operations.

Uploaded by

Aathi
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/ 19

Python: Unit - IV

UNIT - IV
Error Handling:
Python Errors
Error in Python can be of two types i.e. Syntax errors and Exceptions. 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.

The difference between Syntax Error and Exceptions


Syntax Error:
As the name suggest this error is caused by wrong syntax in the code. It leads to the
termination of the program.
Example:
amount = 10000
if(amount>2999) #Syntax Error
print("You are eligible to purchase.")

Exceptions:
Exceptions are raised when the program is syntactically correct but the code resulted in
an error. This error does not stop the execution of the program, however, it changes the normal
flow of the program.
Example:
marks = 10000
a = marks / 0 #Exceptions - ZeroDivisionError
print(a)

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.
✓ ZeroDivisionError: Occurs when a number is divided by zero.
✓ NameError: It occurs when a name is not found. It may be local or global.
✓ IndentationError: If incorrect indentation is given.

Department of CS&IT, S.S.D.M College. 1


Python: Unit - IV

✓ IOError: It occurs when Input Output operation fails.


✓ EOFError: It occurs when the end of the file is reached, and yet operations are
being performed.

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

Department of CS&IT, S.S.D.M College. 2


Python: Unit - IV

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.

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

NotImplementedError
29 Raised when an abstract method that needs to be implemented in an inherited class is not actually
implemented.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop and generate
an error message.
Department of CS&IT, S.S.D.M College. 3
Python: Unit - IV

If you have some suspicious code that may raise an exception, you can defend your
program by placing the suspicious code in a try: block. After the try: block, include an except:
statement, followed by a block of code which handles the problem as elegantly as possible.
Syntax:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
➢ A single try statement can have multiple except statements. This is useful when
the try block contains statements that may throw different types of exceptions.
➢ You can also provide a generic except clause, which handles any exception.
➢ After the except clause(s), you can include an else-clause. The code in the else-
block executes if the code in the try: block does not raise an exception.
➢ The else-block is a good place for code that does not need the try: block's
protection.
Example:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
# Throws error
print ("Fourth element = %d" %(a[3]) )
except IndexError:
print ("An error occurred")

A try statement can have more than one except clause, to specify handlers for different
exceptions. Please note that at most one handler will be executed.

Department of CS&IT, S.S.D.M College. 4


Python: Unit - IV

Example:
try :
a=3
if a < 4 :
# throws ZeroDivisionError for a = 3
b = a/(a-3)
# throws NameError if a >= 4
print ("Value of b = ", b)

except(ZeroDivisionError, NameError):
print ("\nError Occurred and Handled")

Else Clause
In python, can also use else clause on the try-except block which must be present after
all the except clauses. The code enters the else block only if the try clause does not raise an
exception.
Example:
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Finally Keyword
Python provides a keyword finally, which is always executed after try and except
blocks. The finally block always executes after normal termination of try block or after try
block terminates due to some exception.

Department of CS&IT, S.S.D.M College. 5


Python: Unit - IV

Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
try:
k = 5//0 # raises divide by zero exception.
print(k)

except ZeroDivisionError:
print("Can't divide by zero")

finally:
print('This is always executed')

Raising Exception
The raise statement allows the programmer to force a specific exception to occur. The
sole argument in raise indicates the exception to be raised. This must be either an exception
instance or an exception class (a class that derives from Exception).
Syntax:
raise ExceptionType("Error message")
In this syntax, ExceptionType is the type of exception you want to raise, and "Error
message" is an optional error message that provides additional information about the exception.
Example:
age = -5
if age < 0:
raise ValueError("Age cannot be negative")

Department of CS&IT, S.S.D.M College. 6


Python: Unit - IV

In this example, we check if the age variable is negative, and if it is, we raise a
ValueError exception with the error message "Age cannot be negative".
Raise an exception without error message like this,
raise ValueError
Raise an exception using try catch block like this,
Example:
age = -5
try:
if age < 0:
raise ValueError("Age cannot be negative")
except ValueError:
print("Age Error")
Raising exceptions can be useful when you want to indicate that something has gone
wrong in your code. It allows you to interrupt the normal flow of execution and handle the
error in a controlled way.

Data Streams
A data stream refers to a continuous flow of data that is read from or written to a data
source or destination in a sequential manner. Data streams can be of various types, including
file streams, network streams, standard input/output streams, and more.

Standard Data Streams:


Standard Input (stdin): The default input stream where data is read from. You can
read data from stdin using the input() function or by reading from sys.stdin from the sys
module.
Standard Output (stdout): The default output stream where data is written to. You
can write data to stdout using the print() function or by writing to sys.stdout.
Standard Error (stderr): The default error stream where error messages and
diagnostic information are written to. You can write error messages to stderr using the print()
function or by writing to sys.stderr.

Department of CS&IT, S.S.D.M College. 7


Python: Unit - IV

File Streams:
File streams allow reading from or writing to files on disk. Python's built-in open()
function is used to open file streams in various modes, such as read mode ("r"), write mode
("w"), append mode ("a"), binary mode ("b"), etc.

Network Streams:
Network streams enable communication over computer networks using protocols like
TCP/IP and UDP. Python's socket module provides support for creating client and server
sockets to send and receive data over networks.

Third-party Libraries:
Various third-party libraries in Python offer higher-level abstractions for working with
data streams, such as requests for HTTP requests, pandas for data manipulation, paramiko for
SSH connections, pyserial for serial communication, and more. These libraries provide
convenient interfaces and additional functionality for specific use cases.

Use Cases:
✓ Data Processing: Reading data from sensors, logs, or other sources for
processing, analysis, or visualization.
✓ Communication: Sending and receiving data over networks for client-server
communication, web scraping, API requests, etc.
✓ Data Storage: Writing data to files or databases for storage and retrieval.
✓ Data Integration: Integrating data streams from multiple sources or systems
for aggregation, transformation, or synchronization.

Access Modes Writing


File Handling
File handling is an important part of any web application. Python has several functions
for creating, reading, updating, and deleting 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.

Department of CS&IT, S.S.D.M College. 8


Python: Unit - IV

open Function
➢ The key function for working with files in Python is the open() function.
➢ The open() function takes two parameters; filename, and mode.
➢ There are four different methods (modes) for opening a file.
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists

"t" - Text - Default value. Text mode


"b" - Binary - Binary mode (e.g. images)

Syntax:
file object = open(file_name [, access_mode][, buffering])
➢ 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.

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

Department of CS&IT, S.S.D.M College. 9


Python: Unit - IV

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.

wb
6 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+
Opens a file for both writing and reading. Overwrites the existing file if
7
the file exists. If the file does not exist, creates a new file for reading and
writing.

wb+
Opens a file for both writing and reading in binary format. Overwrites the
8
existing file if the file exists. If the file does not exist, creates a new file
for reading and writing.

a
Opens a file for appending. The file pointer is at the end of the file if the
9
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
Opens a file for appending in binary format. The file pointer is at the end
10
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+
Opens a file for both appending and reading. The file pointer is at the end
11
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+
Opens a file for both appending and reading in binary format. The file
12
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.
Department of CS&IT, S.S.D.M College. 10
Python: Unit - IV

List of all attributes related to file object

S.No. Attribute & Description

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

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

file.name
3
Returns name of the file.

file.softspace
4
Returns false if space explicitly required with print, true otherwise.

Example:
f = open("testFile.txt")
print "Name of the file: ", f.name
print "Closed or not : ", f.closed
print "Opening mode : ", f.mode
print "Softspace flag : ", f.softspace

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:
f = open("testFile.txt")
print "Name of the file: ", f.name

f.close()

Department of CS&IT, S.S.D.M College. 11


Python: Unit - IV

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)
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example:
#Writing
f = open("testFile.txt", "w")
f.write( "Python is a great language.\nYeah its great!!\n")
f.close()
#Appending
f = open("textfile.txt", "a")
f.write("Now the file has more content!")
f.close()
f = open("textfile.txt", "r") #read the file after the appending:
print(f.read())

Create a New File


To create a new file in Python, use the open() method, with one of the following
parameters:
"x" - Create - will create a file, returns an error if the file exist.
"a" - Append - will create a file if the specified file does not exist.
"w" - Write - will create a file if the specified file does not exist.
Example:
f = open("myfile.txt", "x")

Open a File
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the
content of the file.

Department of CS&IT, S.S.D.M College. 12


Python: Unit - IV

Example:
f = open("textfile.txt", "r")
print(f.read())
If the file is located in a different location, need to specify the file path,
f = open("D:\\myfiles\textfile.txt", "r")
print(f.read())

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:
f = open("textfile.txt", "r")
print(f.read(5))

Read Lines
Return one line by using the readline() method
Example:
f = open("textfile.txt", "r")
print(f.readline())
By looping through the lines of the file, can read the whole file, line by line.
Example:
f = open("textfile.txt", "r")
for x in f:
print(x)

Delete a File
To delete a file, you must import the OS module, and run its os.remove() function.
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
Example:
import os
os.remove("textfile.txt")

Department of CS&IT, S.S.D.M College. 13


Python: Unit - IV

The rename() Method


The rename() method takes two arguments, the current filename and the new filename.
Example:
import os
os.rename("textfile.txt", "textfile1.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:
import os
if os.path.exists("textfile.txt"):
os.remove("textfile.txt")
else:
print("The file does not exist")

Pipes as Data Streams


Using pipes as data streams involves establishing communication channels between
processes to exchange data. In Python, you can achieve this using the subprocess module,
which provides functions for creating and interacting with subprocesses, including the ability
to set up pipes for interprocess communication.

Creating Pipe
To create a pipe in Python, you can use the subprocess.Popen class with the
stdin=subprocess.PIPE, stdout=subprocess.PIPE, or stderr=subprocess.PIPE arguments to
specify that a pipe should be created for the standard input, output, or error streams,
respectively.
Example:
import subprocess
# Create a subprocess with a pipe for stdin
child_process = subprocess.Popen(["python", "child_process.py"],
stdin=subprocess.PIPE)

Department of CS&IT, S.S.D.M College. 14


Python: Unit - IV

Writing to the Pipe (Parent Process):


In the parent process, you can write data to the pipe using the stdin.write() method of
the Popen object. Make sure to close the pipe after writing data.
Example:
# Write data to the pipe
child_process.stdin.write(b"Hello, child process!")
child_process.stdin.close()

Reading from the Pipe (Child Process):


In the child process, you can read data from the pipe using standard input (sys.stdin) or
the file descriptor obtained from stdin.fileno().
Example:
import sys
# Read data from stdin (pipe)
data = sys.stdin.buffer.read()
# Process the received data
print("Received data:", data.decode())

Handling Large Data:


For large data volumes, consider reading and writing data in chunks to avoid memory
issues. You can use a loop to read/write data iteratively.
Example:
# Read and write data in chunks
chunk_size = 1024
while True:
chunk = sys.stdin.buffer.read(chunk_size)
if not chunk:
break
# Process the chunk or write it to another pipe

Closing the Pipe:


After writing data to the pipe, it's essential to close it to signal the end of input.
Similarly, ensure to close the pipe in the child process after reading data.

Department of CS&IT, S.S.D.M College. 15


Python: Unit - IV

Example:
# Close the pipe after writing data
child_process.stdin.close()

Error Handling:
Always handle exceptions, such as BrokenPipeError, IOError, or
subprocess.CalledProcessError, when working with pipes to ensure robustness and reliability.

Use Cases:
➢ Interprocess communication (IPC) between Python scripts or external
programs.
➢ Implementing producer-consumer patterns, where one process produces data
and another consumes it.
➢ Building data processing pipelines, where data flows from one process to
another for transformation or analysis.

Handling IO Exceptions
Handling IO (Input/Output) exceptions in Python is essential for ensuring that your
code gracefully handles errors related to reading from or writing to files, network connections,
or other IO operations. These exceptions can occur due to various reasons, such as file not
found, permission denied, network errors, and so on. Proper error handling helps in making
your code more robust and reliable.

Using try-except Blocks:


You can handle IO exceptions using try and except blocks. Wrap the IO operation inside
a try block, and catch specific exceptions using except blocks.
You can use a finally block to execute cleanup code, such as closing files or releasing
resources, regardless of whether an exception occurs.
Example:
try:
with open("example.txt", "r") as file:
content = file.read()
except FileNotFoundError:

Department of CS&IT, S.S.D.M College. 16


Python: Unit - IV

print("File not found.")


except PermissionError:
print("Permission denied.")
except IOError as e:
print("IO error:", e)
except Exception as e:
print("An unexpected error occurred:", e)
finally:
# Ensure file is closed
if 'file' in locals():
file.close()

Common IO Exceptions:
✓ FileNotFoundError: Raised when a file or directory is not found.
✓ PermissionError: Raised when permission is denied while trying to access a file
or directory.
✓ IOError: Base class for IO-related errors.
✓ OSError: Base class for operating system-related errors.

Handling IO exceptions appropriately ensures that your code can gracefully recover
from errors and handle exceptional conditions, leading to more reliable and robust applications.

Directories
Directories in Python involves tasks such as creating, listing, navigating, and deleting
directories. Python's built-in os and os.path modules provide functions for interacting with
directories and paths.

Creating Directories:
You can create a directory using the os.makedirs() function. This function creates all
intermediate-level directories if they don't exist.
Example:
import os

Department of CS&IT, S.S.D.M College. 17


Python: Unit - IV

# Create a directory
os.makedirs("my_directory")

Listing Directory Contents:


You can list the contents of a directory using the os.listdir() function. It returns a list of
all files and directories in the specified directory.
Example:
# List directory contents
contents = os.listdir("my_directory")
print(contents)

Directory Exists:
You can check if a directory exists using the os.path.exists() function.
Example:
# Check if directory exists
if os.path.exists("my_directory"):
print("Directory exists")
else:
print("Directory does not exist")

Change Directory:
You can change the current working directory using the os.chdir() function.
Example:
# Change current working directory
os.chdir("my_directory")

Remove Directory:
You can remove a directory using the os.rmdir() function. Note that the directory must
be empty for this function to succeed.
Example:
# Remove directory
os.rmdir("my_directory")

Department of CS&IT, S.S.D.M College. 18


Python: Unit - IV

Recursively Removing Directories:


To remove a directory and all its contents recursively, you can use the shutil.rmtree()
function from the shutil module.
Example:
import shutil
# Recursively remove directory
shutil.rmtree("my_directory")

Other Operations:
➢ Getting the Current Working Directory: Use os.getcwd() to get the current
working directory.
➢ Joining Paths: Use os.path.join() to join directory and file names into a single
path.
➢ Splitting Paths: Use os.path.split() to split a path into directory and file name
components.
➢ Checking if a Path is a Directory: Use os.path.isdir() to check if a path refers to
a directory.

Working with directories in Python is straightforward using the os and os.path modules.
These modules provide a wide range of functions for performing various directory-related
operations, making it easy to manage directories in your Python programs.

Department of CS&IT, S.S.D.M College. 19

You might also like