Fix Python – Directory-tree listing in Python

Question

Asked By – Matt

How do I get a list of all files (and directories) in a given directory in Python?

Now we will see solution for issue: Directory-tree listing in Python


Answer

This is a way to traverse every file and directory in a directory tree:

import os

for dirname, dirnames, filenames in os.walk('.'):
    # print path to all subdirectories first.
    for subdirname in dirnames:
        print(os.path.join(dirname, subdirname))

    # print path to all filenames.
    for filename in filenames:
        print(os.path.join(dirname, filename))

    # Advanced usage:
    # editing the 'dirnames' list will stop os.walk() from recursing into there.
    if '.git' in dirnames:
        # don't go into any .git directories.
        dirnames.remove('.git')

This question is answered By – Jerub

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0