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.

os.remove(path_of_file)

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,

import os

# Remove a file
os.remove('/home/somedir/Documents/python/logs')

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.

import os

filePath = '/home/somedir/Documents/python/logs';

# As file at filePath is deleted now, so we should check if file exists or not not before deleting them
if os.path.exists(filePath):
    os.remove(filePath)
else:
    print("Can not delete the file as it doesn't exists")

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.

import os

# Handle errors while calling os.remove()
try:
    os.remove(filePath)
except:
    print("Error while deleting file ", filePath)

Remove a file using os.ulink()

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

os.unlink(filePath)

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

# Handle errors while calling os.ulink()
try:
    os.ulink(filePath)
except:
    print("Error while deleting file ", filePath)

Complete example is as follows,
import os


def main():
    filePath = '/home/somedir/Documents/python/logs/sample.log';

    # Remove a file
    os.remove('/home/somedir/Documents/python/logs/sample.log')
    FileNotFoundError
    # As file at filePath is deleted now, so we should check if file exists or not not before deleting them
    if os.path.exists(filePath):
        os.remove(filePath)
    else:
        print("Can not delete the file as it doesn't exists")

    # Handle errors while calling os.remove()
    try:
        os.remove(filePath)
    except:
        print("Error while deleting file ", filePath)

    # Handle errors while calling os.ulink()
    try:
        os.ulink(filePath)
    except:
        print("Error while deleting file ", filePath)


if __name__ == '__main__':
    main()


 

 

Join a list of 2000+ Programmers for latest Tips & Tutorials