How to Delete a File using Python

The ‘os‘ module can be used to delete a file in Python:

import os

file_path = r"Path where the file is stored\file_name.file_extension"

os.remove(file_path)

Example of Deleting a File using Python

(1) Let’s suppose that a file called ‘Products‘ is stored in a ‘Test‘ folder, where the full file path is:

C:\Users\Ron\Desktop\Test\Products.csv

(2) To delete the ‘Products‘ file using the ‘os‘ module:

import os

file_path = r"C:\Users\Ron\Desktop\Test\Products.csv"

os.remove(file_path)

If you run the above script (adjusted to your file_path), the ‘Products‘ file will be deleted.

Few notes to consider:

  • Place the ‘r‘ letter before your file path to avoid unicode errors.
  • The os.remove() function permanently deletes the file specified and doesn’t send it to the recycle bin or trash.

Leave a Comment