This is the folder tree:
FOLDER\\
\\1\\file
\\2\\file
\\3\\
\\4\\file
The script should scan (loop) for each folder in FOLDER and check if the sub-folders are empty or not. If they are, they must be deleted.
My code, until now, is this:
folders = ([x[0] for x in os.walk(os.path.expanduser('~\\Desktop\\FOLDER\\DIGITS\\'))])
folders2= (folders[1:])
This scan for folders and, using folders2
begin from the firs folder in DIGITS
.
In DIGITS
there are numbered directories: 1,2,3,4,etc
Now what? Tried using os.rmdir
but it gives me an error, something about string. In fact, folders2
is a list, not a string, just saying...
Deleting Directories (Folders) In Python you can use os. rmdir() and pathlib. Path. rmdir() to delete an empty directory and shutil.
Click to open My Computer. Choose the Search tab at the top line. In the opening Search Menu, set Size filter to Empty (0 KB) and check All subfolders option. From the list of the files and folders that don't take up any disk space, right-click the empty folder(s) and select Delete.
Delete an Empty Directory (Folder) using rmdir()We can delete them using the rmdir() method available in both the os module and the pathlib module. In order to delete empty folders, we can use the rmdir() function from the os module.
rmtree('/path/to/dir') - and that this command will delete the directory even if the directory is not empty. On the other hand, os. rmdir() needs that the directory be empty.
Not sure what kind of error you get, this works perfectly for me:
import os
root = 'FOLDER'
folders = list(os.walk(root))[1:]
for folder in folders:
# folder example: ('FOLDER/3', [], ['file'])
if not folder[2]:
os.rmdir(folder[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With