Remove or Delete File - Python os.remove() - Examples


Python - Delete File

To remove or delete a file using Python, call the remove() method of the os library with the path to the file passed as an argument to the function.

In this tutorial, we will learn how to delete a file and explore different scenarios that may occur during the deletion process, such as handling missing files.


Examples

1. Remove a Given File

This example demonstrates how to delete a file named data.txt, located in the same directory as the program.

Python Program

import os

os.remove('data.txt')
print('The file is removed.')

Explanation (Step-by-Step):

  1. Import the os module, which provides functions to interact with the file system.
  2. Call os.remove('data.txt') to delete the file named data.txt from the current working directory.
  3. If the file exists, it will be removed, and the program will continue to execute the next line.
  4. Print the message 'The file is removed.' to indicate successful deletion.

If the file is located in a different directory, specify the absolute path to the file:

Python Program

import os

os.remove('C:\workspace\python\data.txt')
print('The file is removed.')
Python Remove or Delete File - os.remove()

Explanation (Step-by-Step):

  1. Import the os module.
  2. Use os.remove() with the absolute file path 'C:\workspace\python\data.txt' to delete the file located in a specific directory.
  3. If the file exists at the specified path, it will be deleted.
  4. Print the message 'The file is removed.' to confirm the operation.

2. Try to Remove a File That Does Not Exist

This example shows the error raised when attempting to delete a file that does not exist at the specified path.

Python Program

import os

os.remove('C:\workspace\python\aslkdjfa.txt')
print('The file is removed.')

Output

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'aslkdjfa.txt'

Explanation (Step-by-Step):

  1. Import the os module.
  2. Attempt to delete a file named 'aslkdjfa.txt' located at the path 'C:\workspace\python\' using os.remove().
  3. Since the file does not exist, Python raises a FileNotFoundError.
  4. The error includes details such as the error code [WinError 2] and the path of the missing file.
  5. To avoid this error, check if the file exists using os.path.exists() before calling os.remove().

Summary

In this tutorial, we explored how to delete a file using the os library's remove() function in Python, including scenarios where the file exists or does not exist.


Python Libraries