Print contents of a folder

Viewed 39

Here is my example.

Ex:

I have a folder that contains another 3 folders (FoldA, FoldB, and FoldC), a .txt file, and a .png file.

I have the following working code which works to print the contents a folder or directory.

import pathlib

rd = pathlib.Path("E:\\Location\\MainFolder")

for td in rd.iterdir():
    print(td)

The output is:

E:\Location\MainFolder\FoldA

E:\Location\MainFolder\FoldB

E:\Location\MainFolder\FoldC

E:\Location\MainFolder\image.png

E:\Location\MainFolder\text.txt


Does anyone know a quick way to only print the folders and not any other file type (.txt, .bmp, .png, etc.)? I've tried using .is_dir but it still prints everything.

Thanks in advance!

1 Answers

probably you did if td.is_dir with is a function, so you need to execute it like this:

import pathlib

rd = pathlib.Path(".")

for td in rd.iterdir():
    if td.is_dir():
        print(td)

Kinda common problem with pathlib at beginning :)

Related