Unit-V - File Input Output and Exceptions Handling
Unit-V - File Input Output and Exceptions Handling
A file object allows us to use, access and manipulate all the user accessible files. One can read and write
any such files.
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.
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
open() returns a file object, and is most commonly used with two arguments:
open(filename, mode)
The second argument is another string containing a few characters describing the way in which the file
will be used. mode can be:
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
Example:
read_data = file.read()
print(read_data)
Output:
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):
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 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.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
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
print(read_data)
Output:
some 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 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
read_file = file.read(10)
position = file.tell()
reposition = file.seek(0, 0)
read_file = file.read(20)
file.close()
Output:
Some
To use this module you need to import it first and then you can call any related functions.
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
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
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.
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:
Output:
runfile('C:/Users/Pranav/untitled3.py', wdir='C:/Users/Pranav')
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:
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 –
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
Exception Description
AssertionError Raised when an assert statement fails.
AttributeError Raised when an attribute reference or assignment fails.
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.
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.
PermissionError Raised when trying to run an operation without the adequate access
rights.
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.
1 Exception
2 StopIteration
Raised when the next () method of an iterator does not point to any object.
3 SystemExit
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
7 FloatingPointError
8 ZeroDivisionError
Raised when division or modulo by zero takes place for all numeric types.
9 AssertionError
10 AttributeError
Raised when there is no input from either the raw_input() or input() function
and the end of file is reached.
12 ImportError
13 KeyboardInterrupt
Raised when the user interrupts program execution, usually by pressing Ctrl+c.
14 LookupError
15 IndexError
16 KeyError
17 NameError
18 UnboundLocalError
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
23 IndentationError
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
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
When a Python script raises an exception, it must either handle the exception immediately otherwise it
terminates and quits.
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
try:
......................
except ExceptionI:
except ExceptionII:
......................
else:
• 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")
except IOError:
else:
fh.close()
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")
except IOError:
else:
a = [1, 2, 3]
try:
print ("Second element = %d" %(a[1]))
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.
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)
def fun(a):
if a < 4:
# throws ZeroDivisionError for a = 3
b = a/(a-3)
try:
fun(3)
fun(5)
Output
The output above is so because as soon as python tries to access the value of b, NameError occurs.
Output:
-5.0
a/b result in 0
Syntax:
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# execute if no exception
finally:
# Some code .....(always executed)
Example:
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
Output:
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).
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):
NameError: Hi there
Examples:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
except Exception:
print("can't divide by zero")
print(Exception)
else:
Output:
Enter a:10
Enter b:0
<class 'Exception'>
Example
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b;
print("a/b = %d"%c)
except:
else:
Output:
Enter a:10
Enter b:0
Example 3:
try:
a = int(input("Enter a:"))
b = int(input("Enter b:"))
c = a/b
print("a/b = %d"%c)
except Exception as e:
print(e)
else:
Output:
Enter a:10
Enter b:0
division by zero
Example: Multiple Exceptions
try:
a=10/0;
except(ArithmeticError, IOError):
print("Arithmetic Exception")
else:
print("Successfully Done")
Output:
Arithmetic Exception
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
try:
if(age<18):
raise ValueError
else:
except ValueError:
Output:
try:
except ValueError as e:
print(e)
Output:
Example 3
try:
if b is 0:
raise ArithmeticError
else:
print("a/b = ",a/b)
except ArithmeticError:
Enter a:10
Enter b:0