Deleting files and folders in Python

Deleting files

Use os.remove()

import os
os.remove(filename)

Deleting folders

Use os.rmdir()

import os
os.rmdir(dirname)

You will get an OSError if the directory is not empty.

Deleting whole trees

You can delete a non-empty directory and all of its descendants with shutil.rmtree()

shutil.rmtree(dirname)