0
0
PythonHow-ToBeginner · 3 min read

How to Delete a File in Python: Simple Guide

To delete a file in Python, use the os.remove() function from the os module by passing the file path as a string. This function deletes the specified file immediately if it exists.
📐

Syntax

The basic syntax to delete a file in Python is:

  • os.remove(path): Deletes the file at the given path.
  • path is a string representing the file location.

You must first import the os module to use this function.

python
import os
os.remove('filename.txt')
💻

Example

This example shows how to create a file, check it exists, delete it using os.remove(), and then confirm it is deleted.

python
import os

filename = 'testfile.txt'

# Create a file
with open(filename, 'w') as f:
    f.write('Hello!')

# Check if file exists before deleting
if os.path.exists(filename):
    os.remove(filename)
    print(f"'{filename}' has been deleted.")
else:
    print(f"'{filename}' does not exist.")
Output
'testfile.txt' has been deleted.
⚠️

Common Pitfalls

Common mistakes when deleting files include:

  • Trying to delete a file that does not exist, which raises a FileNotFoundError.
  • Not having permission to delete the file, causing a PermissionError.
  • Passing a directory path instead of a file path, which raises an IsADirectoryError.

Always check if the file exists before deleting to avoid errors.

python
import os

filename = 'missingfile.txt'

# Wrong way: directly deleting without checking
# os.remove(filename)  # This raises FileNotFoundError if file missing

# Right way: check before deleting
if os.path.exists(filename):
    os.remove(filename)
else:
    print(f"Cannot delete '{filename}': file does not exist.")
Output
Cannot delete 'missingfile.txt': file does not exist.
📊

Quick Reference

Summary tips for deleting files in Python:

  • Import os module first.
  • Use os.remove(path) to delete a file.
  • Check file existence with os.path.exists(path) before deleting.
  • Handle exceptions like FileNotFoundError and PermissionError for safer code.

Key Takeaways

Use os.remove(path) to delete a file in Python.
Always import the os module before deleting files.
Check if the file exists with os.path.exists(path) to avoid errors.
Handle exceptions like FileNotFoundError for safer file deletion.
Do not use os.remove on directories; it only works on files.