Our primary goal is to remove a file if it exists; if it does not, we need to avoid the error.
Here are five ways in Python:
- Using os.remove() along with os.path.exists()
- Using send2trash (Soft delete)
- Using os.unlink()
- Using pathlib.Path.unlink()
- Using shutil.rmtree() (For removing a directory)
Method 1: Using os.remove() along with os.path.exists()
The os.remove() method is a built-in Python method that removes a file from the system. However, it raises a FileNotFoundError if the file does not exist.
For checking file existence, we can use the os.path.exists() method before executing the os.remove() method. That way, we are adding one layer before removal to avoid the program crashing.
Let’s say we have a file called app.cpp in our current working directory.
We will remove the app.cpp file using the code below:
import os if os.path.exists("app.cpp"): os.remove("app.cpp") print("The file has been deleted successfully") else: print("The file does not exist!") # Output: The file has been deleted successfully
If you try to execute the above script again, you will get the following output.
The file does not exist!
Before removing the file, it checks if it exists; in our case, it does not. So, it returns the “File does not exist!” output.
If the file exists but lacks write permissions, the os.remove() function raises a PermissionError.
Use try-except when deleting multiple files in a loop to avoid repetitive existence checks, improving performance.
Method 2: Using send2trash
There is a third-party library called send2trash that you can use to soft delete the files instead of permanently deleting them. It uses the trash/recycle-bin instead.
Let’s say we have a folder named “docs” and inside that, we need to delete all the files that have an extension .log.
So, there may be multiple files to delete. For each ‘.log’ file found, it prints its path and uses ‘send2trash’ to move it to the system trash, avoiding permanent deletion.
Here is the screenshot of the “docs” folder:
In the above screenshot, you can see that there are 3 log files. We will delete those 3 log files based on the .log extension.
Install the send2trash library if you have not already installed the command below:
pip install send2trash
With the help of the pathlib module, we can use the Path().rglob() method to find the .log files.
from pathlib import Path from send2trash import send2trash log_files = Path('docs').rglob('*.log') for file_path in log_files: try: send2trash(file_path) print(f"Deleted: {file_path}") except Exception as e: print(f"Failed to delete {file_path} — {e}") # Output: # Deleted: docs/hello.log # Deleted: docs/new.log # Deleted: docs/main.log
From the output, you can see that all three 3 log files have been deleted. Now, let’s verify this in the file system.
If you check the Recycle Bin/Trash, you will see these three files as well, because they do not permanently delete the files from the system.
Method 3: Using os.unlink()
The os.unlink() method removes a file. It’s identical to the os.remove() method, which is why it’s rarely used.
You can check if the file exists using os.path.isfile() and then use this method to remove a file safely.
I have created an app.cpp file in the current directory again.
Here is the code to delete it:
import os file_path = 'app.cpp' # Check if the file exists if os.path.isfile(file_path): try: os.unlink(file_path) print(f"File '{file_path}' has been deleted.") except OSError as error: print(f"Error: {error} - File '{file_path}' could not be deleted.") else: print(f"File '{file_path}' does not exist.") # Output: File 'app.cpp' has been deleted.
If the file exists, it will be removed. If it does not, it will execute the except block, which prints “Error while deleting file”.
Method 4: Using pathlib.Path.unlink()
The Path.unlink() method from the pathlib module also removes a file, with the advantage that it can make your code more readable and expressive.
Here is a file before deleting:
from pathlib import Path file_path = Path('app.cpp') # Check if the file exists if file_path.is_file(): try: file_path.unlink() print(f"File '{file_path}' has been deleted.") except OSError as error: print(f"Error: {error} - File '{file_path}' could not be deleted.") else: print(f"File '{file_path}' does not exist.") # Output: File 'app.cpp' has been deleted.
Method 5: Using shutil.rmtree()
The shutil.rmtree() function is used to remove a directory and all of its contents, including all subdirectories and files.
If you are looking for a method that can delete a file or directory, you can use this approach. Even if you are unsure whether the path is a file or a directory, shutil.rmtree() can be used for directories, but it’s overkill for single files.
Let’s create an app.cpp file again inside the new_dir directory, and we will remove this directory.
import os import shutil dir_path = 'new_dir' # Check if the directory exists if os.path.exists(dir_path) and os.path.isdir(dir_path): try: shutil.rmtree(dir_path) print(f"Directory '{dir_path}' has been deleted.") except OSError as error: print(f"Error: {error} - Directory '{dir_path}' could not be deleted.") else: print(f"Directory '{dir_path}' does not exist.") # Output: Directory 'new_dir' has been deleted. # Automatically app.cpp file will be deleted if it exists.
You can see that the “new_dir” has been deleted along with the app.cpp file inside it.
That’s all!