Search code examples
pythonfiledirectorylistdir

how to check if the given path contains a subfolders and are not empty in python?


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 ?


Solution

  • 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))