0

I want to check if the given path contains folders and files and if the folders are empty or not.

i wrote a chunk of script that list all files and folders but the problem that if the folder is empty it will display it as a file. while this is not correct.

code:

src = "I:/"

path = os.listdir(src)
try:
    for files in path:
        # print(files)
        if os.path.isdir(files):
            print("folder name :****{}****".format(files))
        else:
            print("file name: {}".format(files))
except Exception as e:
    print(e)

what i am doing wrong and how to check if the subfolders are empty or not ?

Dev Dj
  • 169
  • 2
  • 14
  • What is wrong with your current code? As an aside, `except Exception:` is bad practice. – AMC Feb 05 '20 at 05:47
  • why is the exception syntax wrong ?? and how to make it good practice? – Dev Dj Feb 05 '20 at 05:54
  • _why is the exception syntax wrong ?? and how to make it good practice?_ You can find some good resources on the subject right here on Stack Overflow: https://stackoverflow.com/questions/54948548/what-is-wrong-with-using-a-bare-except, https://stackoverflow.com/questions/4990718/about-catching-any-exception – AMC Feb 05 '20 at 18:42

1 Answers1

0

You need os.walk() to do this.

src = "I:/"
for dirpath, dirnames, files in os.walk(src):
    if files:
        print("Directory {0} has files in it".format(dirpath))
        print("Files are : {0}".format(files))
    else:
        print("Diretory {0} is empty".format(dirpath))

Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
  • so i can't do it using os.listdir() rather than os.walk() ? – Dev Dj Feb 05 '20 at 05:33
  • You said you want to check if subfolders are empty or not. `os.listdir()` lists all the files and dirs in a given path. To check for subfolders you will have create a loop and the do `os.listdir()` again. It can be a little confusing. – Prashant Kumar Feb 05 '20 at 05:36
  • i want to check if the given path contains files and subfolders than if the subfolders are empty or not – Dev Dj Feb 05 '20 at 05:38
  • `os.walk()` does exactly this thing. It returns directories and files in given folder in different variables. Would request you to read about `os.walk()` once. It's really helpful for tasks like this. – Prashant Kumar Feb 05 '20 at 05:41
  • i tried your answer it is good but id did not return the empty folder yet it display the that the folder contain files without list them. – Dev Dj Feb 05 '20 at 05:53
  • If the directory is empty, code goes to the else condition. And I have printed the `dirpath` in that. If you want directory name you can just print variable `dirname`. – Prashant Kumar Feb 05 '20 at 09:12