Sunday, April 20, 2025

Python Delete Files, Folders

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

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...