Many times developers need to delete files. Perhaps he created the file by mistake or no longer needs it. For whatever reason, there are ways to delete files through Python without having to manually look up files and do so through UI interaction.

There are several ways to delete files using Python, but the best way is as follows:

  • OS. The remove ()Delete the file
  • OS. Unlink ()Delete files. It is aRemove ()The Unix name of the method.
  • Shutil. Rmtree ()Delete the directory and everything below it.
  • Pathlib. Path. Unlink ()Used in Python 3.4 and later to delete a single filepathlibThe module.

OS. The remove ()Delete the file

The OS module in Python provides the ability to interact with the operating system. OS belongs to Python’s standard utility module. This module provides a portable way to use operating system-dependent functionality.

The os.remove () method in Python is used to remove file paths. This method cannot delete directories. This method raises OSError if the specified path is a directory.

Note: Directories can be removed using os.rmdir ().

Syntax:

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

os.remove(path)
Copy the code

parameter

  • pathThis is the path or file name to delete.

The return value

The remove () method does not return a 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")
Copy the code

Output:

File removed successfully
Copy the code

Note: In the example above, we deleted the file or the path to the file named testfile.txt. The steps to explain the program flow are as follows:

1. First, we import the OS library because the OS library has the remove () method.

2. We then use the built-in function os.remove () to remove the path to the file.

3. In this example, our sample file is “test_file.txt”. You can place the required files here.

Note: The above example raises an error if there is no file named test_file.txt. Therefore, it is best to check whether a file is available before deleting it.

Example 2: Check for the existence of a file using os.path. Isfile and Remove it using os.remove

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

Let’s learn how to check if a file with a particular 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 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
Copy the code

Output:

File Deleted successfully
Copy the code

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

Example 3: A 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)Copy the code

Output:

Using this program, we will remove all files with the.txt extension from the folder.

Explanation:

  • Import OS module and OS module from OS modulelistdir. You must use thelistdirTo get a list of all the files in a particular folder, and you need an OS module to delete files.
  • my_pathIs the path to the folder that contains all files.
  • We are traversing the files in the given folder.listdirGet a list of all the files in a particular folder.
  • endswithThis command is used to check whether the file is valid.txtEnd of extension. When we delete all in the folder.txtFile, if the condition can be verified.
  • If the file name starts with.txtThe end of the extension we will useOS. The remove ()The delete function deletes the file. This function takes the path to the file as an argument.my_path + file_nameIs the full path to the file we’re deleting.

Example 4: A Python program that deletes all files in a folder

To delete all files in a particular directory, simply 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))
Copy the code

Output:

Deleted pythonpool\test1.txt
Deleted pythonpool\test2.txt
Deleted pythonpool\test3.txt
Deleted pythonpool\test4.txt
Copy the code

In this example, we will delete all files in the PYTHonPool folder.

Note: An error may be reported if the folder contains other subfolders, 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 an extension.

Delete Python files using os.unlink ()

Os.unlink () is an alias of os.remove (). In Unix OS, delete is also called unlink.

Note: All functions and syntax are the same as os.unlink () and os.remove (). Both are used to delete Python file paths. Both are methods of performing deletion 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 maintainers of the module believe that many programmers might switch from low-level programming in C to Python, where library functions and low-level system calls are called unlink (), while others might use RM commands (short for “delete”) or shell scripts to simplify the language.

Use shutil.rmtree () to delete the Python file

Shutil.rmtree () : Deletes the specified directory, all subdirectories, and all files. This feature is particularly 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 deletes directories and their contents.

Syntax:

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

Parameters:

Path: a path-like object representing the file path. A path-like object is a string or byte object that represents a path.

Ignore_errors: If ignore_errors is true, errors resulting from deletion failures are ignored.

Oneerror: If ignore_errors is false or ignored, such errors are handled by calling the handler specified by onerror.

Let’s look at an example of deleting a file using a Python script.

Example: A 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) 
Copy the code

Output:

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

Delete files in Python using pathlib.path.unlink ()

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 a Path object pointing to the file and call the unlink () method on that object:

Example: A 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()
Copy the code

In the example above, the path () method is used to retrieve the file path, while the unlink () method is used to delete the file at the specified path.

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

conclusion

In this article, you learned about Python’s various methods for deleting files. The syntax for deleting files or folders using Python is very simple. However, please note that once the above command is executed, your files or folders will be permanently deleted.

If you still have any questions about Python deleting files. Let us know in the comment section below.

Read more

Top 10 Best Popular Python Libraries of 2020 \

2020 Python Chinese Community Top 10 Articles \

5 minutes to quickly master the Python timed task framework \

Special recommendation \

\

Click below to read the article and join the community