How to handle exception while file handling in python?

Description

To handle the exception while handling the file using python3.

  Try

  Except

  Finally

Some types of error: IOError

  If the file cannot be opened.

ImportError

  If python cannot find the module.

ValueError

  Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.

KeyboardInterrupt

  Raised when the user hits the interrupt key (normally Control-C or Delete).

EOFError

  Raised when one of the built-in functions (input() or raw_input()) hits an end-of-file condition (EOF) without reading any data.

#in this sample we are going to see IOError and how to handle that.

 

#read a file using loop and readlines()

#os package for detect the file directory

import os

os.chdir(‘/home/soft27/.config/spyder-py3′)

#exception handling when file is not in the directory

try:

list=[]

for line in open(‘read_it.txt’,’r’).readlines():

list.append(line)

#slicing

list=list[0:10]

str1=”.join(list)

print(“—–IOError—–“)

print(str1)

#IOError handling

except IOError as e:

print(“file missing({})”.format(e))

Leave Comment

Your email address will not be published. Required fields are marked *

clear formSubmit