Print contents of a folder

Question:

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:LocationMainFolderFoldA

E:LocationMainFolderFoldB

E:LocationMainFolderFoldC

E:LocationMainFolderimage.png

E:LocationMainFoldertext.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!

Asked By: GooseCake

||

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 🙂

Answered By: How about nope
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.