In this tutorial, we’ll learn how to delete a file in Python. In Python, we know how to read from and write to files. Let’s have a look at the delete command in Python today.
Assume we create a file and then execute various actions on it, such as reading and writing. We won’t need the file again once we’ve finished evaluating various types of data; in certain circumstances, we won’t even need it in the future. How can we remove the file at this point? In this lesson, we are going to learn that.
Methods to Delete a File in Python
Let us take a look at the three different methods using which we can delete files in Python.
- os module
- shutil module
- pathlib module
Method 01: Using the os module
The os module in Python includes several simple methods for deleting or removing files as well as empty directories. 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!")
We’ve used an if-else statement to prevent throwing an exception if the file directory doesn’t exist. The procedure isfile() verifies that the file with the name ‘new file.txt’ exists.
Another method, rmdir(), is provided by the os module and may be used to delete or remove an empty directory. Check out the following example:
import os os.rmdir('directory')
Note: There must be no files in the directory. The procedure returns an OSerror if it includes any content.
Method 02: Using the shutil module
Shutil is yet another Python method for deleting files that makes it simple for a user to remove a file or its whole directory (including all its contents).
rmtree() is a method in the shutil module that recursively removes a directory and its contents. Let’s have a look at how to put it to use:
import shutil shutil.rmtree('/test/')
The directory ‘/test/’ is deleted for the above-mentioned code. Most significantly, all of the contents in the directory are remove as well.
Method 03: Using the pathlib module
pathlib is a built-in Python module for Python 3.4 and above. Using this pre-defined module, we may delete a file or an empty directory.
Let’s have a look at an example:
import pathlib file=pathlib.path("test/new_file.txt") file.unlink()
The path() function is use to get the file path in the above example, while the unlink() method is use to unlink or delete the file for the supplied path.
For files, the unlink() function is useful. An OSError is generated if a directory is specified. One of the methods previously outlined can be used to delete a directory.
Conclusion of Delete a File in Python
We’ve already covered os.remove(), os.unlink(), and pathlib. To remove a single file, use path.unlink(), os.rmdir(), or pathlib. Shutil.rmtree() recursively deletes a directory and all of its contents. Path.rmdir() deletes an empty directory.
Be extra careful when removing files or directories, because once you delete the file, it cannot be easily recover.