1

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!

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
GooseCake
  • 33
  • 8
  • 2
    Can you *show* the code you've tried? – Konrad Rudolph Sep 15 '22 at 13:38
  • The `.is_dir()` method is what you would need in this case. Please, show us how you tried to use it. – Matej Jeglič Sep 15 '22 at 13:44
  • Does this answer your question? [Getting a list of all subdirectories in the current directory](https://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory) – Michael M. Sep 15 '22 at 13:44
  • Wow, I feel dumb now lol I actually tried it like the answer provided below which works but I didn’t do the if : … I just put “td.is_dir()”. Thanks everyone! – GooseCake Sep 15 '22 at 13:50

1 Answers1

0

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

How about nope
  • 752
  • 4
  • 13