0

how do I delete empty directories on my D:\ drive let's say.... I'm writing in Python and for some reason, my code doesn't work. I can't figure out the problem

Thanks for the help... code:

import os
path = 'D:\\'
dire = []

for file in os.listdir(path):
    print(file)
    dire.append(file)

try:
    for file in dire:
        new_path = 'D:\{0}'.format(file+"\\")
        if os.listdir(new_path) == []:
            os.rmdir(file)
            print(file+" has been deleted")
        else:
            print("directory "+file+" is not empty")

except (FileNotFoundError, NotADirectoryError):
    print(file+" could not be located, or opened...")
    dire.remove(file)
roy
  • 53
  • 1
  • 1
  • 4
  • Define "it doesn't work". – Bart Friederichs Aug 23 '17 at 15:17
  • Are you wanting to delete `file` or `new_path`? Why does `new_path` get directory separator appended if it's potentially a file and not a directory? You might want to look into `os.path.isdir` and `os.path.isfile` to more effectively check if a path is a directory or a file. – tdube Aug 23 '17 at 15:19
  • Check this page your answer seems to be given https://stackoverflow.com/questions/6215334/finding-empty-directories-in-python – Subrata Sarkar Aug 23 '17 at 15:26

0 Answers0