In this article we will discuss how to remove a file if only it exists and how to handle other types of exceptions using os.remove() & os.ulink().

How to remove a file using os.remove()

python ‘s os module provides a function to remove the file i.e.

It accepts the file path as argument and deletes the file at that path. File path can be relative to current working directory or an absolute path.

For example,

It will delete the file at given path.

Error handling in os.remove()

os.remove() can throw OSError if,

  • A file don’t exists at given path. Error message will be like,
    • [WinError 2] The system cannot find the file specified
    • FileNotFoundError: [Errno 2] No such file or directory
  • User doesn’t have access to it file at given path. Error message will be like,
    • [WinError 5] Access is denied
  • Given path is a directory. Error message will be like,
    • IsADirectoryError: [Errno 21] Is a directory

Therefore it’s always good to check for errors while calling os.remove() i.e.

Remove a file if exists using os.remove()

As os.remove() can throw OSError if given path don’t exists, so we should first check if file exists then remove i.e.

But still if the given file path points to a directory instead of file or user don’t have access to the given file, then os.remove() can still throw error.

Therefore, best way is to use try catch while calling os.remove() i.e.

Remove a file using os.ulink()

python provides an another function in os module to remove files i.e.

It’s exactly similar to os.remove(). Example,

Complete example is as follows,



Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.