Several Methods of Deleting Files in Python

  • 2021-09-20 21:04:03
  • OfStack

Preface

Many times developers need to delete files. Maybe he created the file by mistake, or he no longer needs it. For whatever reason, there are 1 way to delete a file through Python without having to manually find the file and delete it through UI interaction.

There are many ways to delete files using Python, but the best methods are as follows:

os. remove () Delete file os. unlink () Deletes files. It is the Unix name of the remove () method. shutil. rmtree () deletes the directory and everything below it. pathlib. Path. unlink () is used in Python 3.4 and later to remove the single file pathlib module.

os. remove () Delete file

The OS module in Python provides the ability to interact with the operating system. OS is a standard utility module for Python. This module provides a portable way to use functions that depend on the operating system.

The os. remove () method in Python is used to delete the file path. This method cannot delete the directory. If the specified path is a directory, the method throws OSError.

Note: You can use os. rmdir () to delete directories.

Syntax:

Here is the syntax for the remove () method to delete an Python file:

os.remove(path)

Parameter

path-This is the path or file name to delete.

Return value

The remove () method did not return a value.

Let's look at an example of using the os. remove function to delete an Python file.

Example 1: A basic example of deleting 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 delete 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 files you want here.

Note: If there is no file named test_file. txt, the above example throws an error. Therefore, it is best 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 delete it

In Example 1, we just deleted the files that existed in the directory. The os. remove () method searches the working directory for files to delete. Therefore, it is best to check whether the file exists.

Let's learn how to check whether a file with a specific name is available in this path. We are using os. path. isfile to check file availability.


#importing the os Library
import os

#checking if file exist 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 throwig an error

Output:

File Deleted successfully

In the above example, we only added the os. pasth. isfile () method. This method helps us find out whether the file exists in a specific location.

Example 3: The Python program deletes 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.

Explanation:

Import os module and listdir from os module. You must use listdir to get a list of all files in a specific folder, and you need an os module to delete files. my_path is the path to the folder that contains all the files. We are traversing the files in the given folder. listdir is used to get a list of all files in a specific folder. endswith is used to check whether a file ends with the. txt extension. When we delete all. txt files in the folder, we do this if the conditions can be verified. If the file name ends with the. txt extension, we use the os. remove () function to delete the file. This function takes the path of the file as an argument. my_path + file_name is the full path to 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 gets the names of all folder contents, whether they are files or subfolders. Therefore, try to make the schema more specific (for example *. *) to get only content with extensions.

Delete the Python file using os. unlink ()

os. unlink () is an alias for os. remove (). In Unix OS, deletion is also referred to as unlink.

Note: All functionality and syntax are the same as os. unlink () and os. remove (). They are all used to delete Python file paths. Both are methods of performing the deletion function in the os module of the Python standard library.

It has two names, aliases: os. unlink () and os. remove ()

The possible reason for providing two aliases for the same function is that the maintainer of this module thinks that many programmers may switch from the underlying programming of C to Python, where library functions and underlying system calls are called unlink (), while others may use rm commands (short for "delete") or shell scripts to simplify the language.

Delete an Python file using shutil. rmtree ()

shutil. rmtree (): Deletes the specified directory, all subdirectories, and all files. This feature is particularly dangerous because it can delete everything without checking. As a result, you can easily lose data using this feature.

rmtree () is a method under the shutil module that recursively deletes directories and their contents.

Syntax:

Shutil. rmtree (path, ignore_errors = False, onerror = None)

Parameters:

path: Path-like object representing the file path. A ClassPath object is a string or byte object that represents a path. ignore_errors: If ignore_errors is true, errors caused by deletion failures are ignored. oneerror: If ignore_errors is false or is ignored, this type of error is handled by calling the handler specified by onerror.

Let's look at an example of deleting files using python script.

Example: Python program that uses Shutil. Rmtree () to delete files


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

Output:

It deletes the entire directory of files within Test, including the Test folder itself.

Using pathlib. Path. unlink () to delete files 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 handling file system paths for different operating systems.

To delete a file using the pathlib module, create an Path object that points to the file, and then call the unlink () method on that object:

Example: Python program that uses Pathlib to delete files


#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, while the unlink () method is used to delete the file with the specified path.

The unlink () method applies to files. If a directory is specified, OSError is thrown. To delete the directory, we can use one of the methods discussed earlier.

Conclusion

In this article, we learned about various methods for Python to delete files. The syntax for deleting files or folders using Python is very simple. Please note, however, that once you execute the above command, your files or folders will be permanently deleted.


Related articles: