简体   繁体   中英

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.

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM