Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pathlib – print contents of a folder

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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 🙂

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading