close

[Solved] How to handle FileNotFound when “try .. except IO” does not catch it?

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error How to handle FileNotFound when “try .. except IO” does not catch it? in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How to handle FileNotFound when “try .. except IO” does not catch it Error Occurs?

Today I get the following error How to handle FileNotFound when “try .. except IO” does not catch it? in python.

How To Solve handle FileNotFound when “try .. except IO” does not catch it Error ?

  1. How To Solve handle FileNotFound when “try .. except IO” does not catch it Error ?

    To Solve How to handle FileNotFound when “try .. except IO” does not catch it Error If filename is a pathlib.Path object instead of a string, we can call its .unlink() method instead of using os.remove().

  2. How to handle FileNotFound when “try .. except IO” does not catch it?

    To Solve How to handle FileNotFound when “try .. except IO” does not catch it Error If filename is a pathlib.Path object instead of a string, we can call its .unlink() method instead of using os.remove().

Solution 1


A more pythonic way would be:

try:
    os.remove(filename)
except OSError:
    pass

Although this takes even more lines and looks very ugly, it avoids the unnecessary call to os.path.exists() and follows the python convention of overusing exceptions.

It may be worthwhile to write a function to do this for you:

import os, errno

def silentremove(filename):
    try:
        os.remove(filename)
    except OSError as e: # this would be "except OSError, e:" before Python 2.6
        if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
            raise # re-raise exception if a different error occurred

Solution 2

I prefer to suppress an exception rather than checking for the file’s existence, to avoid a TOCTTOU bug. Matt’s answer is a good example of this, but we can simplify it slightly under Python 3, using contextlib.suppress():

import contextlib

with contextlib.suppress(FileNotFoundError):
    os.remove(filename)

If filename is a pathlib.Path object instead of a string, we can call its .unlink() method instead of using os.remove(). In my experience, Path objects are more useful than strings for filesystem manipulation.

Since everything in this answer is exclusive to Python 3, it provides yet another reason to upgrade.

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read