Python OS – Delete a file with exception handling

In this post we will be creating a Python script that will delete a file within a specified directory, for this example we will be using the OS module which provides a portable way of using operating system dependent functionality.

See the snippet of code below. We use a try-except block and handle the exception with an output message should the file not exist.

import os

someFile='File.txt'

try:
    os.remove(someFile)
except OSError as e:  
    print ("Error: %s - %s." % (e.filename, e.strerror))

Leave a Reply