Many times a user or a python programmer needs to delete a file. The reason maybe he/she created the file by mistake, or there is no need for that file anymore. Whatever the reason, there are ways to Python Delete file without manually finding the file and deleting them by UI.
There are multiple ways to Delete a File in Python but the best ways are the following:
- os.remove() removes a file.
- os.unlink() removes a file. it is a Unix name of remove() method.
- shutil.rmtree() deletes a directory and all its contents.
- pathlib.Path.unlink() deletes a single file The pathlib module is available in Python 3.4 and above.
Python Delete File Using os.remove()
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.
Note: You can use
os.rmdir() can be used to remove the directory.
Following is the syntax for remove() method to delete a Python file −
- path − This is the path or file name, which is to be removed.
The remove() method doesn’t return value.
Let’s check out some of the examples to Delete Python File using os.remove function.
Example 1: Basic Example to Remove a File Using os.remove() Method.
# Importing the os library import os # Inbuilt function to remove files os.remove("test_file.txt") print("File removed successfully")
File removed successfully
Explanation: In the above example we have deleted the file or removed the path of the file named testfile.txt. Steps Explaining how the program flow goes are:
1. First, we have imported the os library because the remove() method is present inside the os library.
2. Then we have used the inbuilt function os.remove() to delete the path of the file.
3. In this example, our sample file is “test_file.txt”. You can place your desired file here.
Note: If there is no file named test_file.txt the above example will throw an error. So it’s better to check first whether the file is available or not before deleting the file.
Example 2: Checking if File Exists using os.path.isfile and Deleting it With os.remove
In example 1, we have just deleted the file present in the directory. The os.remove() method will search the file to remove in the working directory. So it’s always better to check if the file is there or not.
Let’s learn how to check if the file with that name available in that path or not. We are using os.path.isfile to check the availability of 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
File Deleted successfully
In the above example, we just added os.pasth.isfile() method. This method helps us to find out whether the file exists or not at a particular location.
Example 3: Python Program to Delete 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)
Using this program, we will remove all files from the folder with the .txt extension.
- Import os module and listdir from the os module. listdir is required to get the list of all files in a specific folder and os module is required to remove a file.
- my_path is the path of the folder with all files.
- We are looping through the files in the given folder. listdir is used to get one list of all files in a specific folder.
- endswith is used to check if a file ends with a .txt extension or not. As we are deleting all .txt files in a folder, this if the condition will verify this.
- If the file name is ending with .txt extension, we are removing that file using os.remove() function. This function takes the path of the file as a parameter. my_path + file_name is the complete path for the file we are deleting.
Example 4: Python Program to Delete All Files Inside a Folder
To delete all files inside a particular directory, you simply have to 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))
Deleted pythonpool\test1.txt Deleted pythonpool\test2.txt Deleted pythonpool\test3.txt Deleted pythonpool\test4.txt
In this example, we’re deleting all the files inside the folder pythonpool.
Note: If the folder will contain any sub-folder, then the error may be raised as the
glob.glob() method fetches the names of all the folder contents, whether they’re files or sub-folders. Therefore try to make the pattern more specific such as
*.* to fetch only the contents that have an extension.
Python Delete File Using os.unlink()
os.unlink() is an alias or another name of os.remove() . As in the Unix OS remove is also known as unlink.
Note: All the functionalities and syntax is the same of os.unlink() and os.remove(). Both of them are used to delete the Python file path.
Both are methods in the os module in Python’s standard libraries which performs the deletion function.
It has two names, aliases: os.unlink() and os.remove()
The likely reason for providing both aliases to the same function is that the maintainers of this module considered it likely that many programmers would be coming up to Python from lower-level programming in C, where the library function and underlying system call is named unlink() while others would, likely, be coming down to the language from using the shell or scripting where the command is rm (short for “remove”).
Python Delete File Using shutil.rmtree()
shutil.rmtree(): Removes the specified directory, all subdirectories, and all files. This function is especially dangerous because it removes everything without checking (Python assumes that you know what you’re doing). As a result, you can easily lose data using this function.
rmtree() is a method under the shutil module which removes a directory and its contents in a recursive manner.
Shutil.rmtree(path, ignore_errors=False, onerror=None)
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.
Let’s see an example do delete a file using python script.
Example: Python Program to Delete a File Using shutil.rmtree()
# 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)
It will delete the entire directory of files inside Test including the Test folder itself.
Python Delete File Using pathlib.Path.unlink()
The pathlib module is available in Python 3.4 and above. If you want to use this module in Python 2 you can install it with pip.
pathlib provides an object-oriented interface for working with filesystem paths for different operating systems.
To delete a file with the
pathlib module, create a
Path object pointing to the file and call the
unlink() method on the object:
Example: Python Program to Delete a File Using pathlib
#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 whereas, the
unlink() method is used to unlink or remove the file for the specified path.
The unlink() method works for files. If a directory is specified, an OSError is raised. To remove a directory, we can resort to one of the previously discussed methods.
References and Must Read
- How to Convert String to Lowercase in Python
- How to Calculate Square Root in Python
- Python User Input | Python Input () Function | Keyboard Input
- Best Book to Learn Python in 2020
In this article, we have learned various best ways to Python Delete File. The syntax to delete a file or folder using Python is quite simple. However, please be advised that once you execute the above commands, your file or folder would be permanently deleted.
If you still have any doubts regarding Python Delete File. Do let us know in the comment section below.