Python 3 – os.remove() Method
In Python, the os
module provides an easy way to interact with the file system. With the os
module, you can create, edit and delete files and directories on your computer.
One of the methods provided by the os
module for deleting files is the remove()
method. The os.remove()
method deletes a file in the specified path. This method removes the file if it exists and raises an error if the file does not exist.
The syntax of the os.remove()
method is as follows:
os.remove(path)
where path
is the file path to be deleted.
Let’s take a look at an example of how to use the os.remove()
method in Python:
import os
# specify the path of the file to be deleted
path = "C:/Users/User/Desktop/myfile.txt"
# delete the file
os.remove(path)
print("File deleted successfully!")
In the above example, we first import the os
module into our Python script. We then specify the path of the file we want to delete. Finally, we call os.remove()
with the path of the file as an argument to delete the file. If the file deletion is successful, a message “File deleted successfully!” will be printed to the console.
Let’s look at another example where we delete multiple files at once using a for loop:
import os
# specify the paths of the files to be deleted
files_to_delete = [
"C:/Users/User/Desktop/myfile1.txt",
"C:/Users/User/Desktop/myfile2.txt",
"C:/Users/User/Desktop/myfile3.txt",
]
# loop through the files and delete them
for file in files_to_delete:
os.remove(file)
print("Files deleted successfully!")
In the above example, we use a list to store the paths of the files we want to delete. We then loop through the list using a for loop and call os.remove()
with each file path as an argument to delete the files.
Conclusion
The os.remove()
method in Python provides an easy way to delete files in the file system. This method can be used to delete files one at a time or in a batch. It is important to note that the os.remove()
method will raise an error if the file does not exist, so it is recommended to check for the existence of the file before attempting to delete it.