Delete a File in Python

To delete a file in Python, you can use the os.remove() function from the built-in os module or the unlink() function from the pathlib module. These functions allow you to delete a specific file if it exists on the system.


Examples to Delete a File

1. Deleting a File Using os.remove()

In this example, we will use the os.remove() function to delete a file named sample.txt. This method works for most operating systems.

main.py

</>
Copy
import os

# Specify the file name
file_name = "sample.txt"

# Delete the file
os.remove(file_name)

print(f"{file_name} has been deleted successfully.")

Explanation:

  1. We import the os module, which provides functions to interact with the operating system.
  2. A variable file_name is defined with the name of the file to be deleted (sample.txt).
  3. The os.remove(file_name) function is called to delete the file.
  4. A message is printed confirming that the file has been deleted successfully.

Output:

sample.txt has been deleted successfully.

2. Handling File Not Found Error

If the file does not exist, calling os.remove() will raise a FileNotFoundError. To avoid this error, we can check if the file exists before attempting to delete it.

main.py

</>
Copy
import os

# Specify the file name
file_name = "sample.txt"

# Check if file exists before deleting
if os.path.exists(file_name):
    os.remove(file_name)
    print(f"{file_name} has been deleted successfully.")
else:
    print(f"Error: {file_name} does not exist.")

Explanation:

  1. We import the os module.
  2. The file name is stored in the variable file_name.
  3. The os.path.exists(file_name) function is used to check if the file exists.
  4. If the file exists, it is deleted using os.remove(file_name).
  5. If the file does not exist, a message is printed to inform the user.

Output (when file exists):

sample.txt has been deleted successfully.

Output (when file does not exist):

Error: sample.txt does not exist.

3. Deleting a File Using pathlib.Path.unlink()

The pathlib module provides an object-oriented way to handle file paths. We can use the unlink() method from Path to delete a file.

main.py

</>
Copy
from pathlib import Path

# Specify the file path
file_path = Path("sample.txt")

# Delete the file
file_path.unlink()

print(f"{file_path} has been deleted successfully.")

Explanation:

  1. We import the Path class from the pathlib module.
  2. The file path is stored in the file_path variable using Path("sample.txt").
  3. The unlink() method is called to delete the file.
  4. A message is printed confirming the deletion.

Output:

sample.txt has been deleted successfully.

4. Handling Errors Using Try-Except

We can use a try-except block to handle any errors that occur while deleting the file.

main.py

</>
Copy
import os

# Specify the file name
file_name = "sample.txt"

# Try deleting the file with error handling
try:
    os.remove(file_name)
    print(f"{file_name} has been deleted successfully.")
except FileNotFoundError:
    print(f"Error: {file_name} does not exist.")
except PermissionError:
    print(f"Error: Permission denied to delete {file_name}.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Explanation:

  1. We import the os module.
  2. The file name is stored in the file_name variable.
  3. The try block attempts to delete the file using os.remove(file_name).
  4. If the file is not found, a FileNotFoundError is caught, and an error message is displayed.
  5. If there is a permission issue, a PermissionError is caught, and an error message is displayed.
  6. Any other unexpected errors are caught and displayed.

Output (when file does not exist):

Error: sample.txt does not exist.

Conclusion

In Python, you can delete a file using:

  1. os.remove() – Deletes a file from the system.
  2. os.path.exists() – Checks if the file exists before deletion.
  3. Path.unlink() – Deletes a file using the pathlib module.
  4. Try-Except – Handles errors during file deletion.

Using these techniques ensures safe and error-free file deletion.