My Coding > Programming language > Python > Python FAQ > Python: How to list all files and subdirectories in a directory

Python: How to list all files and subdirectories in a directory

Crawling through all subdirectories within given directory in order to find all files is a traditional task of walking through the tree. It is not necessary to create your own algorithm of such walk. In Python you can use function walk() from library os to do this task.

os.walk(directory) will create a generator with 3 tuples for each subdirectory in the tree. The final path to subdirectories and files you can restore with the function os.path.join(rood, path)

Very simple script will give the full list of all files and all subdirectories, which you can analyse further:


directory = "./mydir/"

for root, subdir, files in os.walk(directory):
    # list of all files
    for F in files:
        print(os.path.join(root, F))

    # list of all SubDirrectories
    for SD in subdir:
        print(os.path.join(root, DB))


Published: 2022-05-25 15:05:09
Updated: 2022-05-25 15:05:42

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.