In our tutorial on working with files in Python we learned how to manage them. In this tutorial, we will learn how to delete files in Python.
Let’s assume that after successfully creating a file, we perform some operations on it, such as reading and writing. Once we have finished using the file to analyze various datasets, it may be that in some cases we will not need it in the future.
Let’s take a look at the different ways in which we can delete files in Python.
1 Using the os module
os module in Python provides several easy to use methods with which we can delete or delete a file as well as an empty directory. Take a close look at the code below:
import os if os.path.isfile (’/ Users / test / new_file.txt’): os .remove (’/ Users / test / new_file.txt’) print (" success ") else: print (" File doesn’t exists! ")
Here we used the if-else statement to avoid the exception that can be thrown if the file directory does not exist. The
isfile () method checks for the existence of a file with the filename && # 8216; new_file.txt & # 8217 ;.
os module provides us with another method,
rmdir () , which can be used to deleting or deleting an empty directory. For example:
import os os.rmdir (’directory’)
Note: the directory must be empty. If it contains any content, the method returns an OSerror.
2 Usage shutil module
Shutil &this is another file deletion method that allows the user to easily delete a file or its entire directory (including all its contents).
rmtree () &it is a method of the shutil module that recursively deletes a directory and its contents. Let’s see how to use it:
import shutil shutil.rmtree (’/ test /’)
For the above code deleted directory / test /. Most importantly, all content inside the directory is also removed.
3 Using the pathlib module
pathlib &this is a built-in Python module available for Python 3.4+.
Here’s an example:
import pathlib file = pathlib.path ( "test / new_file.txt") file.unlink ()
In the above example, the
path () method is used to get the file path, while the
unlink ( ) is used to unlink or delete a file at the specified path.
The unlink () method works with files. If a directory is specified, an OSError is thrown. To remove a directory, we can use one of the previously discussed methods.
- https: //docs.pytho n.org/3/library/os. html # os.remove
- https://docs.python.org/3/library/ pathlib.html