It is very easy to delete a file using Python. There are a few different ways to delete a file, but os.remove() is the simplest of them all.

The os module provides large number functions to interact with an operating system and the file system is part of every of them. We will focus on the os.remove() method for now.

The syntax for the remove() method is as follows:

  • path(sting) takes the file location.
  • If the file does not exist, it will raise an error: FileNotFoundError or the path indicates a directory instead of file then will be: IsADirectoryError (use os.rmdir() instead)

Here is an example for removing file(s) from a peculiar location.

import os

def remove_file(path):
if os.path.isfile(path):
        return True
    return False

location = “/home/user/sample” 
if os.path.isdir(location):
    for filename in os.listdir(location):
        remove_file(os.path.join(location, filename))

This code will delete all the files present in /home/user/sample except directories, so it will never end up deleting everything from root (“/”).

Support On Demand!