To delete files we will use os module, and remove()
function:
import os
print("WARNING, files will be deleted")
print("-" * 50)
os.remove("external.txt")
os.remove("external_2.txt")
If we try to delete directory with content using rmdir()
, operation will fail:
import os
print("Trying to delete Full Folder Will Fail")
print("-" * 50)
os.rmdir("FULL_FOLDER")
Result:
Traceback (most recent call last):
File "C:\Python38-64\ARCHIVE\learning-python.py", line 6, in <module>
os.rmdir("FULL_FOLDER")
OSError: [WinError 145] The directory is not empty: 'FULL_FOLDER'
>>>
That function can be used only on empty folders:
import os
print("With rmdir You Can delete only Empty Folder")
print("-" * 50)
os.rmdir("EMPTY_FOLDER")
Result:
With rmdir You Can delete only Empty Folder
--------------------------------------------------
>>>
What if you must delete folder and everything in it ? In that case, use "shutil" module and rmtree()
function:
import shutil
print("With shutil.rmtree() You Can delete Full Folder")
print("-" * 50)
shutil.rmtree("FULL_FOLDER")
Result:
With shutil.rmtree() You Can delete Full Folder
--------------------------------------------------
>>>
Well done.
It's time to learn about Try, Except and Finally blocks.
No comments:
Post a Comment