Skill - Delete a file or folder in python
Skills Required
- Setup python development environment
- Basic Printing in Python
- Commenting in Python
- Managing Variables in python
- strings in python
- raw strings in python
- Handling errors in python
- Check if file or folder is present
Please make sure to have all the skills mentioned above to understand and execute the code mentioned below. Go through the above skills if necessary for reference or revision
In this post, we will learn to delete a file or folder in python using remove
and rmdir
functions
Delete a file using ‘remove’ function
# import the os module
import os
# specify the file we desire to delete
fPath = r'C:\Users\Nagasudhir\Documents\test.txt'
# check if the file exists first
fileExists = os.path.exists(fPath)
if fileExists:
# use remove function to delete the file if it exists
os.remove(fPath)
else:
print("File does not exist")
We checked if the file exists at first because, remove
function will raise an OSError
if the desired file does not exist.
Delete a folder along with sub-folders and files using ‘shutil.rmtree’ function
# import the os module and shutil module
import shutil
import os
# specify the folder we desire to delete
fPath = r'C:\Users\Nagasudhir\UnwantedFolder'
# check if folder is present using isdir function
folderExists = os.path.isdir(fPath)
if folderExists:
# use remove function to delete the file if it exists
shutil.rmtree(fPath)
else:
print("Folder does not exist")
Video
The video for this post can be seen here
Online Interpreter
Although we recommend to practice the above examples in Visual Studio Code, you can run these examples online at https://www.tutorialspoint.com/execute_python_online.php
References
- https://thispointer.com/python-how-to-remove-a-file-if-exists-and-handle-errors-os-remove-os-ulink/
- https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
Comments
Post a Comment