Exceptions

While we are trying to access files via python, if there are any issue, it will raise an IOError.

There are many scenarios where we can get IOError.

❑ If we attempt to open for reading a file that does not exist, it will throw an IOError.
❑ If we attempt to create a file in a directory that does not exist, it will throw an IOError.
❑ If we attempt to open a file for which we do not have read access, it will throw an IOError.
❑ If we attempt to create a file in a directory for which we do not have write access, it will throw an IOError.
❑ If our computer encounters a disk error (or network error, if we are accessing a file on a network disk), , it will throw an IOError.

Whenever there is any error, our program should handle it gracefully.

This can be done using try block.

In the below code, we are trying to open the file to read inside the try block.

In case if there is any issue, the code inside the except block will execute.

OS Module

The major use of OS module is that whenever we need to get more information about files or directories from our file system, we can use the OS module.

We need to import it first in our program as shown below to use it.

import OS

Using OS module, we can perform lot of activities like retrieving the file name, listing the files in the directory, finding out if the current path is file or folder, converting relative path to absolute path and vice versa.

All these activities can be performed irrespective of different OS version like windows, linux, etc.

For example: In windows, file paths are separated by backslash. However, in other OS like MAC, it is forward slash.

We don’t need to handle it in our code for different OS, it is automatically taken care by OS module.

Leave a comment

Design a site like this with WordPress.com
Get started