Several ways to delete files in Python

There are various ways to delete files using Python, but the best way is as follows:
os.remove() removes a file
os.unlink() deletes a file. It is the Unix name for the remove() method.
shutil.rmtree() deletes a directory and everything below it.
pathlib.Path.unlink() is used in Python 3.4 and later to remove a single file pathlib module.
os.remove() removes a file
The OS module in Python provides functionality for interacting with the operating system. OS belongs to Python’s standard utility modules. This module provides a portable way to use OS-dependent functionality.
The os.remove() method in Python is used to remove a file path. This method cannot delete the directory. If the specified path is a directory, the method will raise OSError.
Note: Directories can be removed using os.rmdir().
syntax:
Following is the syntax of remove() method to delete a Python file:
os. remove(path)
parameter
path – This is the path or filename to delete.
return value
The remove() method has no return value.
Let’s look at some examples of removing Python files using the os.remove function.
Example 1: A basic example of removing a file using the OS.Remove() method.

# Importing the os library
import os

# Inbuilt function to remove files
os.remove("test_file.txt")
print("File removed successfully")
output:
File removed successfully

Explanation: In the above example, we deleted the file or deleted the path of the file named testfile.txt. The steps to explain the program flow are as follows:
1. First, we imported the os library, because the remove() method exists in the os library.
2. We then remove the path to the file using the built-in function os.remove().
3. In this example, our sample file is “test_file.txt”. You can place the required files here.
NOTE: The above example will throw an error if there is no file named test_file.txt. Therefore, it is better to check whether the file is available before deleting it.
Example 2: Use Os.Path.Isfile to check if a file exists and use Os.Remove to remove it
In example 1, we have just deleted the files present in the directory. The os.remove() method will search the working directory for the file to remove. So it’s better to check if the file exists.
Let us learn how to check if a file with a certain name is available in that path. We are using os.path.isfile to check the availability of the file.

#importing the os Library
import os

#checking if file exists or not
if(os.path.isfile("test.txt")):
    
    #os. remove() function to remove the file
    os. remove("demo. txt")
    
    #Printing the confirmation message of deletion
    print("File Deleted successfully")
else:
print("File does not exist")
#Showing the message instead of throwing an error
output:
File Deleted successfully

In the above example, we only added the os.path.isfile() method. This method helps us to find out if a file exists in a particular location.
Example 3: Python program to delete all files with a specific extension

import os
from os import listdir
my_path = 'C:\Python Pool\Test\'

for file_name in listdir(my_path):
    
    if file_name.endswith('.txt'):
      
        os. remove(my_path + file_name)

output:
Using this program we will delete all files with the extension .txt from the folder.
explain:
import the os module and listdir from the os module. You must use listdir to get a list of all files in a specific folder, and you need the os module to delete files.
my_path is the path to the folder containing all the files.
We are iterating over the files in a given folder. listdir is used to get a list of all files in a specific folder.
endswith is used to check if a file ends with a .txt extension. When we delete all .txt files in a folder, this is done if the condition can be verified.
If the filename ends with a .txt extension, we will use the os.remove() function to remove the file. This function takes the path of the file as an argument. my_path + file_name is the full path of the file we want to delete.
Example 4: Python program to delete all files in a folder
To delete all files in a specific directory, just use the * symbol as the pattern string.

#Importing os and glob modules
import os, glob

#Loop Through the folder projects all files and deleting them one by one
for file in glob.glob("pythonpool/*"):
    os. remove(file)
    print("Deleted " + str(file))
output:
Deleted pythonpool\test1.txt
Deleted pythonpool\test2.txt
Deleted pythonpool\test3.txt
Deleted pythonpool\test4.txt

In this example, we will delete all files in the pythonpool folder.
Note: If the folder contains other subfolders, an error may be reported, because the glob.glob() method will get the names of all folder contents, whether they are files or subfolders. So try making the pattern more specific (e.g. *.*) to only get what has the extension.
Use os.unlink() to delete Python files
os.unlink() is an alias for os.remove(). In Unix OS, delete is also known as unlink.
Note: All functions and syntax are the same as os.unlink() and os.remove(). They are both used to remove Python file paths. Both are methods in the os module of the Python standard library that perform the delete function.
It has two names, aliases: os.unlink() and os.remove()
A possible reason for providing two aliases for the same function is that the maintainers of this module believe that many programmers may move from low-level programming in C to Python, where library functions and low-level system calls are called unlink(), while others The rm command (short for “remove”) or shell scripts may be used to simplify the language.
Delete Python files using shutil.rmtree()
shutil.rmtree(): Delete the specified directory, all subdirectories and all files. This function is especially dangerous because it deletes everything without checking. As a result, you can easily lose data using this feature.
rmtree() is a method under the shutil module that recursively removes a directory and its contents.
syntax:
Shutil.rmtree(path, ignore_errors=False, onerror=None)
parameter:
path: A path-like object representing a file path. A path-like object is a string or bytes object representing a path.
ignore_errors: If ignore_errors is true, errors caused by deletion failures will be ignored.
oneerror: If ignore_errors is false or ignored, such errors are handled by calling the handler specified by onerror.
Let’s see an example of deleting a file using a python script.
Example: Python program to delete files using Shutil.Rmtree()

# Python program to demonstrate shutil.rmtree()
 
import shut-off
import os
 
# location
location = "E:/Projects/PythonPool/"
 
# directory
dir = "Test"
 
# path
path = os.path.join(location, dir)
 
#removing directory
shutil.rmtree(path)

output:
It will delete the entire directory of files inside Test, including the Test folder itself.
Delete files using pathlib.Path.unlink() in Python
The pathlib module is available in Python 3.4 and later. If you want to use this module in Python 2, you can install it using pip. pathlib provides an object-oriented interface for working with filesystem paths across different operating systems.
To delete a file using the pathlib module, create a Path object pointing to the file, then call the unlink() method on the object:
Example: Python program to delete files using Pathlib

#Example of file deletion by pathlib
 
import pathlib
 
rem_file = pathlib.Path("pythonpool/testfile.txt")

rem_file.unlink()

In the above example, the path() method is used to retrieve the file path and the unlink() method is used to delete the file at the specified path.
The unlink() method works on files. If a directory is specified, OSError is raised. To delete a directory, we can use one of the methods discussed earlier.
in conclusion
In this article, we have learned various ways of deleting files in Python. The syntax to delete a file or folder using Python is very simple. However, be aware that once the above command is executed, your file or folder will be permanently deleted.
If you still have any doubts about Python deleting files. Let us know in the comments section below.