In this short guide, you’ll see how to delete a file or folder using Python.
In particular, you’ll see how to:
- Delete a file
- Delete an empty folder
- Delete a folder with all of its files
To start, here is the general syntax to delete a file or folder:
Delete a file
import os os.remove(r"Path where the file is stored\File Name.File type")
Delete an empty folder
import os os.rmdir(r"Path where the empty folder is stored\Folder name")
Delete a folder with all of its files
import shutil shutil.rmtree(r"Path where the folder and its files is stored\Folder name")
3 Examples of Deleting a File or Folder using Python
Example 1: Delete a file
Let’s suppose that you have an Excel file called Cars.xlsx. For illustration purposes, assume that the file is stored under the following path:
You can then apply the code below (adjusted to your path) in order to delete that file using Python:
import os os.remove(r"C:\Users\Ron\Desktop\Cars.xlsx")
Example 2: Delete an empty folder
Now suppose that you have an empty folder called ‘DeleteMe‘ that is stored under the following path:
To delete that folder using Python:
import os os.rmdir(r"C:\Users\Ron\Desktop\DeleteMe")
Note that if you try to delete a folder that already contains files, you’ll get the following error:
OSError: [WinError 145] The directory is not empty: ‘C:\\Users\\Ron\\Desktop\\DeleteMe’
You may therefore follow the steps below in order to delete a folder that contains files.
Example 3: Delete a folder with all of its files
Let’s suppose that the Cars.xlsx file is stored within the ‘DeleteMe‘ folder.
To delete the folder, and the file within it, you may use the code below (adjusted to your path):
import shutil shutil.rmtree(r"C:\Users\Ron\Desktop\DeleteMe")
Please be advised that once you executed the above commands, your file or folder would be permanently deleted.
You can find out more about the usage of shutil and os, by checking the shutil documentation, as well as the os documentation.