Last Updated: Saturday 14th February 2015
This recipe is a practical example of Python recursive functions, using the os.listdir function. However it is not the most effective method to traverse a directory in Python. os.walk is generally considered the most Pythonic method. For a quick look at how to use os.walk, checkout the article this article for a os.walk example. If you are after a more in-depth look at os.walk, be sure to checkout the article Python's os.walk: An In-depth Guide

So. What's better than making a list of video files on your hard disc drive?

Let's make a list of all video files in a folder, and all other folders in it!

What is a Recursive Function in Python?

Recursion is a concept in computer science. Essentially, it divides a problem into sub-problems. Recursion in Python generally relates to a specific function, method or object, which calls itself to break up these problems. For example, a factorial function would be as follows:

Note that the factorial function calls itself, to break down the factorial problem into sub-problems.

Recursive Python Function: Let's Code!

Let's write the code of traversal within a function, which looks like:

The code is pretty much self-explanatory along with the comments. The recursive Python function print_movie_files takes two arguments: the directory path to search. Then it gets a list of all files and folders in this directory using the os.listdir method. We use a for loop to work on the list,, check whether the filepath is a normal file or directory using the os.path.isfile method. If it's a normal file with an extension in movie_extensions, it will print the filepath. If filepath is a directory, we recursively call the function itself to further process it.

Calling the Recursive Python Function

Now, we call this function within the __main__ scope:

Running the Script

  1. Download and extract the source code zip file (see below), and copy to the directory you wish to search in.
  2. -- OR -- copy the article code to a new file and save it as in the directory you wish to search in.
  3. cd into the directory the movies are in. eg. cd ~/Movies or cd C:\\Users\\Videos.
  4. Run the script with /path/to/python
    • Linux/OSX/Unix: python
    • Windows: C:\\Python34\\python.exe

Tip: On Linux/OSX/Unix you can mark the file as executable, add a Python shebang line at the top of the file, and run it directly. eg.

The code in the script will recursively traverse (look in) all other folders within it, and check for video files. If you're using Windows and have Python IDLE installed, you can just double-click on the file and check the output.

Once again, the os.getcwd method helps us to get the current working directory (cwd), i.e. the directory where the script resides. It calls our just-written function and also has a counter, it counts how many video files it found. Finally, we print all information we have, and wait for a prompt from the user to terminate the program using the input() or raw_input() function (Python changed the name of the raw_input() function to input() when going from Python 2 to Python 3).

To Practice: Try this interactive course on the basics of Lists, Functions, Packages and NumPy in Python.

  • helper

    just for sake of learning new things,
    there is a python function os.walk ( usage: os.walk(name of directory to traverse) ) which will give u names and paths of all files and subfolders recursively all by itself. so a sample usage is here as follows….


    for path, dirname, file_name in os.walk( name of directory to traverse ):

    for i in file_name:

    check = os.path.join(path, i)

    if os.path.isfile( check ):
    # ur code….

    • Jackson Cooper

      Hi there! Very late to reply, but I thought I’d point this out for other readers. This is simply an example of a recursive function in Python. You’re right, it’s not the best method to traverse (or “walk”) a directory in Python. I’ve added a note at the top pointing you to 2 articles on how to traverse a directory in the most efficient (and “Pythonic”) method.

  • Pingback: Recursive File and Directory Manipulation in Python (Part 1) - Python Central()

  • Matthew Herzog

    Dear author. You have not explained how the two snippets work together. Will there be two .py files? I’m not seeing how to call the processFile.

    • Hey Matthew, thanks for the feedback. The article’s been revised – the code snippet should be easier to read, with instructions on how to run it, and a source code download link. Hopefully this should clear things up 🙂

  • Gene Ricky Shaw

    There is a flaw in the code; you need to add “sys” to the line “import os”. When I ran the code, it wouldn’t work until I added it.