Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty folders (Python)

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...

like image 375
BlueTrack Avatar asked Nov 03 '17 10:11

BlueTrack


People also ask

How do I delete an empty directory in Python?

Deleting Directories (Folders) In Python you can use os. rmdir() and pathlib. Path. rmdir() to delete an empty directory and shutil.

How do I get rid of empty folders?

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.

Can you delete a folder with Python?

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.

How do I delete multiple folders in Python?

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.


1 Answers

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])
like image 128
taras Avatar answered Oct 18 '22 19:10

taras