Directory-tree listing in Python


Question

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

1
550
5/22/2018 12:09:35 AM

Accepted 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')
605
4/17/2015 4:54:50 PM

You can use

os.listdir(path)

For reference and more os functions look here:


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon