To delete or remove a file in Python if it exists on disk, you can use the os
module and the os.remove()
function. The os.remove()
function takes the file path as an argument and deletes the file at that path.
Here's an example of how to use the os.remove()
function to delete a file in Python:
import os # Delete a file if it exists file_path = "path/to/file.txt" if os.path.exists(file_path): os.remove(file_path)
In this example, the os.path.exists()
function is used to check if the file exists at the specified path. If the file exists, the os.remove()
function is called to delete it.
It's important to note that the os.remove()
function will raise an OSError
exception if the file does not exist, or if you do not have the necessary permissions to delete the file. To handle these exceptions, you can use a try
-except
block. For example:
import os # Delete a file if it exists, handling the OSError exception file_path = "path/to/file.txt" try: if os.path.exists(file_path): os.remove(file_path) except OSError: print("Failed to delete file")
This will handle any exceptions that may be raised while attempting to delete the file.
It's also important to note that the os.remove()
function will permanently delete the file, and it cannot be recovered. If you want to move the file to a different location instead of deleting it, you can use the shutil
module and the shutil.move()
function.
Consult the Python documentation and online resources for more information on how to delete or remove files in Python.