There are different ways to delete a file or directory in Python lets see all of them.

Delete File or Directory in Python:

As we have seen in our earlier tutorials, python os module has a lot of utility method which helps us to access the os resources, let’s delete a file or a directory using os module.

os.remove()

The following code deletes a specific file.

import os

file= input("Enter file name to delete: ")

if os.path.isfile(file):
    os.remove(file)
else:
    print(f"Error: {file} file not found")

os.unlink()

os.unlink() method deletes the file or symbolic link.

import os

file= input("Enter file name to delete: ")

if os.path.isfile(file):
    os.unlink(file)
else:
    print(f"Error: {file} file not found")

os.rmdir()

os.rmdir() method deletes a directory if it is an empty directory otherwise it throws OSError: [Errno 66] Directory not empty error. So make sure to use this method if there are any files under the directory.

import os

dir= input("Enter file name to delete: ")

if os.path.isdir(dir):
    os.rmdir(dir)
else:
    print(f"Error: {dir} not found")

shutil.rmtree()

If you want to delete a directory which contains files init, the better way is to use Python shutil package. The shutil.rmtree() method removes entire directory tree, it takes two optional parameters ignore_errors=False, onerror=None.

If ignore_errors is true, errors resulting from failed deletions will be ignored; if false or omitted, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception

import os
import shutil

file= input("Enter file name to delete: ")

if os.path.isdir(file):
    shutil.rmtree(file)
else:
    print(f"Error: {file} file not found")

References:

Happy Learning 🙂