One of the things that most python developers don’t care about is dealing with files and directories such as removing the files or any task related to working with files. This article will help you learn the different methods for removing the files and directories.
1. Delete Files Using The Os Module
Working with files is a forgotten skill that many python developers don’t learn, thinking they won’t need this skill. Still, it is helpful in many programs and cases, such as creating a new file, renaming it, adding data to it, and even deleting that file.
Sometimes you want to delete files that are no longer needed, and python makes it easy to perform this action using many libraries and functions. Let’s see the simplest way to delete a file:
import os # File Path file_path = "/home/abdelhakim/Example/File.txt" # Remove File os.remove(file_path)
This module, named os module, is the most used one for deleting a file. You need to specify the file path and then use the os.remove() function to delete the file after you specify its path.
If the file does not exist, it will raise a FileNotFoundError error. We can fix this error by using the try/except statements. Let’s see an example:
import os # File Path file_path = "/home/abdelhakim/Example/File.txt" try: # Remove File os.remove(file_path) # Print a successful message print("File has been deleted successfully") except FileNotFoundError: # Print an Error Message print("The file does not exist")
First, you use the try statement to try the removing file function. If it raises a FileNotFoundError error, it will execute the code inside the except statement without stopping the program.
2. Delete Files Using The Pathlib Module
Python has many libraries that work with files, and one of them is a library called Pathlib. The pathlib library has been introduced only in python 3.4 and above. It has been enhanced in every python version and developed to work with the file system and directories. Let’s see how you can remove a file using pathlib:
import pathlib # File Path file_path = "/home/abdelhakim/Example/File.txt" # Setting The File Path file = pathlib.Path(file_path) # Removing The File file.unlink()
The first thing is adding the file path to a variable called “file_path” and then setting up the path into the pathlib library using the pathlib.Path() function, so this function will know the file path that will be removed. Finally, it will remove the path using the .unlink() function.
3. Removing All Files
We’ve learned different ways of removing the files, but what if you need to remove all the files inside a directory? The os module doesn’t have a function to remove all the files inside a directory, but we can use the for loop to fix this problem. Let me show you an example:
import os # Directory Path directory_path = "/home/abdelhakim/Example/" # Looping Over The Files for file_name in os.listdir(directory_path): # Getting The Full File Path file = directory_path + file_name # Removing The Files os.remove(file)
So first, we’ve specified the directory path, and we loop over the files inside the directory using the for loop and the os.listdir() function that will give you the files inside the directory.
Then we get the full file path by concatenating the directory path and the file name we get from the os.listdir() function. Finally, remove them using the os.remove() function.
4. Deleting Files With a Specific Pattern
We’ve learned in the previous step how you can remove all the files inside a specific directory. What if you want to remove the file with a specific extension like .pdf or .txt? The python language has a module called globe that can fix this issue. Let us see an example:
import glob import os # File Pattern Inside a Directory pattern = "/home/abdelhakim/Example/*.txt" # Adding The Pattern files = glob.glob(pattern) # Delete The Files for file in files: os.remove(file)
The first thing is to specify the directory path, and you need to specify the file extension you want to remove, which is the *.txt you see in the last pattern variable. Then we use the glob.glob() function lets it recognize the file types and store them in a variable called files. Finally, loop over the files and remove them using the os.remove() function.
5. Remove Empty Directories
You’ve seen the different ways for deleting a file with different modules and how to delete only specific file types, but what about the directories? Let’s see how you can remove a folder using the os module:
import os # Directory Path directory = "/home/abdelhakim/Example/" # Remove Directory os.rmdir(directory)
The code is the same as the previous ones, but you need to specify the folder path and use the os.rmdir() function, which stands to remove the directory and specify the folder path. If the directory is not empty, then you will have an error.
6. Remove Non-Empty Directories
The previous step showed you removing the empty directory, but what if the directory has some files and you want to delete them? Let’s see how you can perform this action:
import shutil # Directory Path directory = "/home/abdelhakim/Example/" # Remove Directory shutil.rmtree(directory)
We’ve used the shutil module this time, which comes pre-installed in your python interpreter, and we will use the shutil.rmtree() function removes the directory with all of its files and sub-directories.
Thanks for reading! I hope this article has been helpful for you, and it shows you a skill that many Python developers don’t know about, which is dealing with files and directories and removing them.