Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views26 pages

Unit-V - File Input Output and Exceptions Handling

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)
5 views26 pages

Unit-V - File Input Output and Exceptions Handling

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/ 26

File I/O and Exceptions Handling

File Objects in Python

A file object allows us to use, access and manipulate all the user accessible files. One can read and write
any such files.

File object attributes

A file object has a lot of attributes. You can see a list of all methods and attributes of the file object here:
https://docs.python.org/2.4/lib/bltin-file-objects.html.

Following are some of the most used file object methods –

• close() - Close the file.


• next() - When a file is used as an iterator, typically in a for loop (for example, for line in f: print
line), the next() method is called repeatedly. This method returns the next input line, or raises
StopIteration when EOF is hit.
• read([size]) - Read at most size bytes from the file.
• readline([size]) - Read one entire line from the file.
• seek(offset[, whence]) - Set the file's current position, like stdio's fseek(). The whence argument
is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the
current position) and 2 (seek relative to the file's end).
• tell() - Return the file's current position, like stdio's ftell().
• write(str) - Write a string to the file.
• writelines(sequence) - Write a sequence of strings to the file.

Following are file object's most used attributes −

• closed - bool indicating the current state of the file object.


• encoding - The encoding that this file uses.
• mode - The I/O mode for the file.
• name - If the file object was created using open(), the name of the file. Otherwise, some string
that indicates the source of the file object

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 process of reading and writing to a file is like finding a book and opening a book.

First, the file is located, opened to the first page, then reading/writing begins until it reaches

the end of the file.


The open Function

open() returns a file object, and is most commonly used with two arguments:

open(filename, mode)

The first argument is a string containing the filename.

The second argument is another string containing a few characters describing the way in which the file
will be used. mode can be:

• 'r' when the file will only be read,


• 'w' for only writing (an existing file with the same name will be erased),
• 'a' opens the file for appending; any data written to the file is automatically added to end.
• 'r+' opens the file for both reading and writing.

Normally, files are opened in text mode, that means, you read and write strings from and to the
file, which are encoded in a specific encoding. If encoding is not specified, the default is platform
dependent (see open()).

'b' appended to the mode opens the file in binary mode: now the data is read and written in the
form of bytes objects. This mode should be used for all files that don’t contain text.

In text mode, the default when reading is to convert platform-specific line endings (n on

Unix, rn on Windows) to just n. When writing in text mode, the default is to convert

occurrences of n back to platform-specific line endings.

Example:

file = open("C:\Users\Pranav\Documents\test.txt", "r")

read_data = file.read()

print(read_data)

Output:

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:

# Open a file
file = open('C:/Users/Pranav/Documents/test.txt', 'r')
print ("Name of the file: ", file.name)
print ("Closed or not : ", file.closed)
print ("Opening mode : ", file.mode)
file.close()
read_data = file.read()
print(read_data)
Output:

runfile('C:/Users/Pranav/file_close .py',
wdir='C:/Users/Pranav')
Name of the file: C:/Users/Pranav/Documents/test.txt
Closed or not : False
Opening mode : r
Traceback (most recent call last):

File "C:\Users\Pranav\file_close .py", line 7, in


<module>
read_data = file.read()

ValueError: I/O operation on closed file.

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 a file

file = open('C:/Users/Pranav/Documents/test.txt', 'w+')

file.write("some content \n some more content ")

file.close()
The above method would create test.txt file and would write given content in that file and finally it
would close that file. If you would open this file, it would have following content.

some content

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

Example

file = open('C:/Users/Pranav/Documents/test.txt', 'r')

read_data = file. read()

print(read_data)

Output:

some content

some more content

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('C:/Users/Pranav/Documents/test.txt', "r+")

read_file = file.read(10)

print("Read String is : ", read_file)

# Check current position

position = file.tell()

print ("Current file position : ", position)

# Reposition pointer at the beginning once again

reposition = file.seek(0, 0)

read_file = file.read(20)

print ("Again read String is : ", read_file)

# Close opend file

file.close()

Output:

Read String is : some conte

Current file position : 10

Again read String is : some content

Some

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

Following is the example to rename an existing file test1.txt –

import os

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


os.rename( "test.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

Following is the example to delete an existing file test2.txt –

import os

os.remove("test2.txt")
Handling Exceptions in Python:
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.

Difference between Syntax Error and Exceptions

Syntax Error: As the name suggests this error is caused by the wrong syntax in the code. It leads to the
termination of the program.

Example:

# initialize the amount variable


amount = 10000

# check that You are eligible to


# purchase Dsa Self Paced or not

if(amount > 2999)


print("You are eligible to purchase Dsa Self Paced")

Output:

runfile('C:/Users/Pranav/untitled3.py', wdir='C:/Users/Pranav')

File "C:\Users\Pranav\untitled3.py", line 6

if(amount > 2999)

SyntaxError: invalid syntax

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:

# initialize the amount variable


marks = 100

# perform division with 0


a = marks / 0
print(a)
Output:

Traceback (most recent call last):

File "C:\Users\Pranav\untitled4.py", line 5, in <module>


a = marks / 0

ZeroDivisionError: division by zero

In the above example raised the ZeroDivisionError as we are trying to divide a number by 0.

Python provides two very important features to handle any unexpected error in your Python programs
and to add debugging capabilities in them –

• Exception Handling − This would be covered in this tutorial. Here is a list standard Exceptions
available in Python: Standard Exceptions.
• Assertions –

Built-in Exceptions in Python:


Exceptions should be class objects. The exceptions are defined in the module exceptions. This module
never needs to be imported explicitly: the exceptions are provided in the built-in namespace as well as the
exceptions module.

List of Standard Exceptions (Built-in Exceptions) –

Base Classes

These exceptions are generally used as base classes for other exceptions.

Exception Description
BaseException The base class for all built-in exceptions. It is not meant to be
directly inherited by user-defined classes (for that,
use Exception below).
Exception All built-in, non-system-exiting exceptions are derived from this
class. All user-defined exceptions should also be derived from
this class.
ArithmeticError The base class for built-in exceptions that are raised for various
arithmetic errors. These
are: OverflowError, ZeroDivisionError, FloatingPointError.
BufferError Raised when a buffer related operation cannot be performed.
LookupError The base class for exceptions that are raised when a key or
index used on a mapping or sequence is invalid. These
are: IndexError and KeyError.
Concrete Exceptions

These are the exceptions that are usually raised.

Exception Description
AssertionError Raised when an assert statement fails.
AttributeError Raised when an attribute reference or assignment fails.

When an object does not support attribute references or


attribute assignments at all, TypeError is raised.

EOFError Raised when the input() function hits an end-of-file


condition (EOF) without reading any data.
FloatingPointError Raised when a floating point operation fails.
GeneratorExit Raised when a generator or coroutine is closed.
Technically, this is not an error, and
the GeneratorExit exception directly inherits
from BaseException instead of Exception.
ImportError Raised when the import statement fails when trying to
load a module. This exception is also raised when
the from in from ... import has a name that cannot be
found.
ModuleNotFoundError A subclass of ImportError which is raised by import when
a module could not be located. This exception is also
raised when None is found in sys.modules.
IndexError Raised when a sequence subscript is out of range.
KeyError Raised when a mapping (dictionary) key is not found in
the set of existing keys.
KeyboardInterrupt Raised when the user hits the interrupt key
(typically Control-C or Delete).
MemoryError Raised when an operation runs out of memory but the
situation may still be rescued (by deleting some objects).
NameError Raised when a local or global name is not found. This
applies only to unqualified names.
NotImplementedError This exception is derived from RuntimeError. In user
defined base classes, abstract methods should raise this
exception when they require derived classes to override
the method, or while the class is being developed to
indicate that the real implementation still needs to be
added.
OSError() This exception is raised when a system function returns a
system-related error, including I/O failures such as "file
not found" or "disk full".
OverflowError Raised when the result of an arithmetic operation is too
large to be represented.
RecursionError This exception is derived from RuntimeError. It is raised
when the interpreter detects that the maximum recursion
depth is exceeded.
ReferenceError Raised when a weak reference proxy, created by
the weakref.proxy() function, is used to access an
attribute of the referent after it has been garbage
collected.
RuntimeError Raised when an error is detected that doesn’t fall in
any of the other categories.
StopIteration Raised by the next() function and an
iterator's __next__() method to signal that there are no
further items produced by the iterator.
StopAsyncIteration Must be raised by __anext__() method of an
asynchronous iterator object to stop the iteration.
SyntaxError Raised when the parser encounters a syntax error.
IndentationError Base class for syntax errors related to incorrect
indentation. This is a subclass of SyntaxError.
TabError Raised when indentation contains an inconsistent use of
tabs and spaces. This is a subclass of IndentationError.
SystemError Raised when the interpreter finds an internal error, but
it's not serious enough to exit the interpreter.
SystemExit This exception is raised by the sys.exit() function, and
(when it is not handled) causes the Python interpreter to
exit.
TypeError Raised when an operation or function is applied to an
object of inappropriate type.
UnboundLocalError Raised when a reference is made to a local variable in a
function or method, but no value has been bound to that
variable. This is a subclass of NameError.
UnicodeError Raised when a Unicode-related encoding or decoding
error occurs. It is a subclass of ValueError.
UnicodeEncodeError Raised when a Unicode-related error occurs during
encoding. It is a subclass of UnicodeError.
UnicodeDecodeError Raised when a Unicode-related error occurs during
encoding. It is a subclass of UnicodeError.
UnicodeTranslateError Raised when a Unicode-related error occurs during
encoding. It is a subclass of UnicodeError.
ValueError Raised when a built-in operation or function receives an
argument that has the right type but an inappropriate
value, and the situation is not described by a more
precise exception.
ZeroDivisionError Raised when the second argument of a division or
modulo operation is zero.

OS Exceptions
These exceptions are subclasses of OSError. They get raised depending on the actual system error code.

Exception Description
BlockingIOError Raised when an operation would block on an object (e.g. socket) set for
non-blocking operation.

ChildProcessError Raised when an operation on a child process failed.

ConnectionError A base class for connection-related issues.

BrokenPipeError A subclass of ConnectionError, raised when trying to write on a pipe


while the other end has been closed, or trying to write on a socket which
has been shutdown for writing.

ConnectionAbortedError A subclass of ConnectionError, raised when a connection attempt is


aborted by the peer.

ConnectionRefusedError A subclass of ConnectionError, raised when a connection is reset by the


peer.

FileExistsError Raised when trying to create a file or directory which already exists.
FileNotFoundError Raised when a file or directory is requested but doesn’t exist.

InterruptedError Raised when a system call is interrupted by an incoming signal.

IsADirectoryError Raised when a file operation is requested on a directory.

NotADirectoryError Raised when a directory operation is requested on something which is


not a directory.

PermissionError Raised when trying to run an operation without the adequate access
rights.

ProcessLookupError Raised when a given process doesn’t exist.

TimeoutError Raised when a system function timed out at the system level.

Warnings
The following exceptions are used as warning categories.

Exception Description
Warning Base class for warning categories.
UserWarning Base class for warnings generated by user code.
DeprecationWarning Base class for warnings about deprecated features.
PendingDeprecationWarning Base class for warnings about features which will be
deprecated in the future.
SyntaxWarning Base class for warnings about dubious syntax.
RuntimeWarning Base class for warnings about dubious runtime
behavior.
FutureWarning Base class for warnings about constructs that will
change semantically in the future.
ImportWarning Base class for warnings about probable mistakes in
module imports.
UnicodeWarning Base class for warnings related to Unicode.
BytesWarning Base class for warnings related
to bytes and bytearray.
ResourceWarning Base class for warnings related to resource usage.

Sr.No. Exception Name & Description

1 Exception

Base class for all exceptions

2 StopIteration

Raised when the next () method of an iterator does not point to any object.

3 SystemExit

Raised by the sys.exit() function.

4 StandardError

Base class for all built-in exceptions except StopIteration and SystemExit.

5 ArithmeticError

Base class for all errors that occur for numeric calculation.

6 OverflowError

Raised when a calculation exceeds maximum limit for a numeric type.

7 FloatingPointError

Raised when a floating point calculation fails.

8 ZeroDivisionError

Raised when division or modulo by zero takes place for all numeric types.

9 AssertionError

Raised in case of failure of the Assert statement.

10 AttributeError

Raised in case of failure of attribute reference or assignment.


11 EOFError

Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.

12 ImportError

Raised when an import statement fails.

13 KeyboardInterrupt

Raised when the user interrupts program execution, usually by pressing Ctrl+c.

14 LookupError

Base class for all lookup errors.

15 IndexError

Raised when an index is not found in a sequence.

16 KeyError

Raised when the specified key is not found in the dictionary.

17 NameError

Raised when an identifier is not found in the local or global namespace.

18 UnboundLocalError

Raised when trying to access a local variable in a function or method but no


value has been assigned to it.

19 EnvironmentError

Base class for all exceptions that occur outside the Python environment.

20 IOError

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.

21 IOError

Raised for operating system-related errors.


22 SyntaxError

Raised when there is an error in Python syntax.

23 IndentationError

Raised when indentation is not specified properly.

24 SystemError

Raised when the interpreter finds an internal problem, but when this error is
encountered the Python interpreter does not exit.

25 SystemExit

Raised when Python interpreter is quit by using the sys.exit() function. If not
handled in the code, causes the interpreter to exit.

26 TypeError

Raised when an operation or function is attempted that is invalid for the


specified data type.

27 ValueError

Raised when the built-in function for a data type has the valid type of
arguments, but the arguments have invalid values specified.

28 RuntimeError

Raised when a generated error does not fall into any category.

29 NotImplementedError

Raised when an abstract method that needs to be implemented in an inherited


class is not actually implemented.
What is Exception?
An exception is an event, which occurs during the execution of a program that disrupts the normal flow
of the program's instructions. In general, when a Python script encounters a situation that it cannot cope
with, it raises an exception.

An exception is a Python object that represents an error.

When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.

Exception handling in python:


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 excerpt: statement, followed by a
block of code which handles the problem as elegantly as possible.

Try and except statements are used to catch and handle exceptions in Python. Statements that can raise
exceptions are kept inside the try clause and the statements that handle the exception are written inside
except clause.

Syntax

Here is simple syntax of try....except...else blocks –

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.

Here are few important points about the above-mentioned syntax −

• 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

This example opens a file, writes content in the, file and comes out gracefully because there is no problem
at all –

try:

fh = open("C:/Users/Pranav/Documents/demofle1.txt", "w")

fh.write("This is my test file for exception handling!!")

except IOError:

print ("Error: can't find file or read data")

else:

print ("Written content in the file successfully")

fh.close()

This produces the following result –

Written content in the file successfully

Example

This example tries to open a file where you do not have write permission, so it raises an exception –

try:

fh = open("C:/Users/Pranav/Documents/demofle1.txt", "r")

fh.write("This is demofile1 test file for exception


handling!!")

except IOError:

print ("Error: can't find file or read data")

else:

print ("Written content in the file successfully")

This produces the following result –

Error: can't find file or read data


Let us try to access the array element whose index is out of bound and handle the corresponding
exception.

# Python program to handle simple runtime error


#Python 3

a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))

# Throws error since there are only 3 elements in array


print ("Fourth element = %d" %(a[3]))

except:
print ("An error occurred")
Output:

Second element = 2
An error occurred

In the above example, the statements that can cause the error are placed inside the try statement (second
print statement in our case). The second print statement tries to access the fourth element of the list
which is not there and this throws an exception. This exception is then caught by the except statement.

Catching Specific Exception


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. For example, we can add IndexError in the above
code. The general syntax for adding specific exceptions are –

try:

# statement(s)

except IndexError:

# statement(s)

except ValueError:

# statement(s)

Example: Catching specific exception in Python

# Program to handle multiple errors with one


# except statement
# Python 3

def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)

# throws NameError if a >= 4


print("Value of b = ", b)

try:
fun(3)
fun(5)

# note that braces () are necessary here for


# multiple exceptions
except ZeroDivisionError:
print("ZeroDivisionError Occurred and Handled")
except NameError:
print("NameError Occurred and Handled")

Output

ZeroDivisionError Occurred and Handled

If you comment on the line fun(3), the output will be

NameError Occurred and Handled

The output above is so because as soon as python tries to access the value of b, NameError occurs.

Try with Else Clause


In python, you can also use the 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: Try with else clause

# Program to depict else clause with try-except


# Python 3
# Function which returns a/b
def AbyB(a , b):
try:
c = ((a+b) / (a-b))
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)

# Driver program to test above function


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

Output:

-5.0
a/b result in 0

Finally Keyword in Python


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

Syntax:

try:
# Some Code....

except:
# optional block
# Handling of exception (if required)

else:
# execute if no exception

finally:
# Some code .....(always executed)

Example:

# Python program to demonstrate finally

# No exception Exception raised in try block


try:
k = 5//0 # raises divide by zero exception.
print(k)

# handles zerodivision exception


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

finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:

Can't divide by zero


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

# Program to depict Raising Exception

try:
raise NameError("Hi there") # Raise Error
except NameError:
print ("An exception")
raise # To determine whether the exception was raised or
not

The output of the above code will simply line printed as “An exception” but a Runtime error will also
occur in the last due to the raise statement in the last line. So, the output on your command line will look
like

An exception
Traceback (most recent call last):

File "C:\Users\Pranav\Python Programs\untitled5.py", line 4,


in <module>
raise NameError("Hi there") # Raise Error

NameError: Hi there

Examples:

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 exception 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'>

Example

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

Output:

Enter a:10

Enter b:0

can't divide by zero

Example 3:

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
Example: Multiple Exceptions

try:

a=10/0;

except(ArithmeticError, IOError):

print("Arithmetic Exception")

else:

print("Successfully Done")

Output:

Arithmetic Exception

Example: try...finally block

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

Example: Raising exceptions

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

Example 2: Raise the exception with message

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!

Example 3

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

You might also like