In this article we will discuss different methods to generate a list of all files in directory tree.

Creating a list of files in directory and sub directories using os.listdir()

Python’s os module provides a function to get the list of files or folder in a directory i.e.

It returns a list of all the files and sub directories in the given path.

We need to call this recursively for sub directories to create a complete list of files in given directory tree i.e.

Call the above function to create a list of files in a directory tree i.e.

Creating a list of files in directory and sub directories using os.walk()

Python’s os module provides a function to iterate over a directory tree i.e.

It iterates of the directory tree at give path and for each directory or sub directory it returns a tuple containing,
(<Dir Name> , <List of Sub Dirs> , <List of Files>.
Iterate over the directory tree and generate a list of all the files at given path,

Complete example is as follows,

Output:

 

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.