In this tutorial, we are going to learn how to do the following in python
- Deleting files in python
- Checking if files still exist
- Deleting folders in python
Deleting files in python
To delete a file in python, we can use the remove() which is called from the os module. This remove() method takes only one arguments.
syntax
os.remove(file_name)
Let’s demonstrate with an example
import os
# Delete file2.txtos.remove(“file2.txt”)
After you must have deleted a file and you want to confirm if the file has been deleted or you might to check if the file still exist before deleting. Here is an example to check if a file has been deleted or still exist
import os
if os.path.exists("file2.txt"):os.remove("file2.txt")else:print("The file does not exist")
Deleting folders in python
The method used in deleting folders in python is not that different from the method used when deleting files. When deleting folders we use the os.rmdir() method. Let’s illustrate with an example by deleting a folder called movies
import os
os.rmdir("movies")
Deleting python files with directories
We can remove a directory containing python with a method shutil.rmtree() which is located in the shutil library. With this method, we can clear off an entire directory file. Below is the syntax for the shutil method:
syntax
import shutil
shutil.rmtree(file_path)
Just like the os.remove(), we have imported shutil.rmtree() since an it’s part of an external library.
Let’s illustrate with an example on how to use this method. Let’s remove the final directory which is part of our grade analysis program. To remove the directory we use the following codes
import shutil
path = "/home/school/math/final"shutil.rmtree(path)print("/home/school/math/final has been removed.")
Python Os Error Handling
In some cases when we want to delete a file, the arguments can returned a permission error. There are times when we encounter error problems when using the three methods mention abovet. There is a way to handle these errors in case they arises, we can do this using the try except block. In the example below the compiler executes the lines of code within the try block and if an error is encountered, it will then run the within except block (if the OS Error is raised).
import os
path = "/home/school/math/final"try:os.rmdir(path)print("/home/school/math/final has been deleted.")except OSError as error:print("There was an error.")
CONCLUSION
One of the common things we do in python is to remove files. We use the os.remove() to delete specific files, the os.rmdir() method can be used to remove an empty directory and the shutil.rmtree() method to delete a folder that contains one or more files.
Thank for reading guys. Happy coding
Comments
Post a Comment
Please do not enter any spam link in the comment box.