← Back to Chapters

Python Delete Files

?️ Python Delete Files

? Quick Overview

Python lets you delete files from your system using the os module. You can remove individual files, check if a file exists before deleting it, or loop through a list of filenames. File deletion is permanent, so always be careful to avoid accidental data loss.

? Key Concepts

  • os.remove(path) deletes a file at the given path.
  • os.unlink(path) is effectively the same as os.remove().
  • Use os.path.exists(path) to check if a file exists before deleting.
  • Looping over a list of filenames lets you delete multiple files safely.
  • Trying to delete a non-existing file will raise an error unless you check first.

? Syntax and Theory

To work with file deletion, you first import the os module:

os.remove(path) and os.unlink(path) both remove the file specified by path. If the file does not exist, a FileNotFoundError is raised. That’s why it is a good practice to check with os.path.exists(path) before deleting.

When deleting multiple files, you typically store their names in a list and then iterate over that list, deleting each file that exists and optionally printing a message for those that do not.

? Code Examples

? Delete a single file using os.remove()
import os

os.remove("example.txt")  # Deletes the file named 'example.txt'
? Check if a file exists before deleting
import os

if os.path.exists("example.txt"):  # Check if the file exists before deleting
    os.remove("example.txt")  # Delete the file only when it exists
else:
    print("The file does not exist")  # Handle the case where the file is missing
? Using os.unlink() as an alias of os.remove()
import os

os.unlink("example.txt")  # Deletes the file using os.unlink()
? Deleting multiple files in a loop
import os

files = ["file1.txt", "file2.txt", "file3.txt"]  # List of files to delete

for f in files:  # Loop through each file name
    if os.path.exists(f):  # Delete only if the file exists
        os.remove(f)
    else:
        print(f"{f} does not exist")  # Inform when a file is missing

? Live Output and Explanation

In the multiple-file deletion example, Python will:

  • Delete each file that actually exists in the list.
  • Print a helpful message like file2.txt does not exist when it can’t find a file.

This pattern prevents your script from crashing due to FileNotFoundError and also makes it clear which files were successfully deleted and which were missing.

? Use Cases

  • Cleaning up temporary files generated by your script.
  • Removing exported reports or logs after they are processed.
  • Deleting outdated cache files to save disk space.

? Tips and Best Practices

  • Always check if a file exists before attempting to delete it.
  • Prefer descriptive variable names like file_path instead of just f in real projects.
  • Be extra careful when looping over many files to avoid accidental deletion.
  • Consider logging which files were deleted, especially in automation scripts.
  • Remember that os.remove() and os.unlink() work only for files, not directories.

? Try It Yourself

  • Create a file named example.txt and delete it using os.remove().
  • Create a list of filenames (some real, some fake) and write a script that deletes only the existing files and prints messages for the missing ones.
  • Rewrite your deletion script to use os.unlink() instead of os.remove() and confirm it behaves the same.
  • Modify your script so it asks the user for confirmation (e.g., y/n) before deleting each file.