

The fourth line is how we retrieve the names of files with the extension we want, using the string method endswith to test for a suffix. The third line begins our loop of the argument names, which is a list type. The second line ensures our ext string is lowercase. The first line of our step function is of course our declaration of the function, and inclusion of the default arguments that will be passed directly by os.path.walk. names - the names of all files under dirname.dirname - the directory name for that iteration.ext - the arbitrary argument given to os.path.walk.The three arguments that walk passes on each iteration are: Now let's break it down line-by-line, but first it's very important to point out that the arguments given to step are being passed by directly the os.path.walk function, not by the user. Let's examine the function (which we'll define as "step") we use to print the path names of the files under top that have the file extension we can provide through arg.

It then walks through the directory tree under the top, performing the function at every step.
#WINDOWS 10 LIST DIRECTORY CONTENTS RECURSIVELY HOW TO#
In a way this recipe is a combination of How to Traverse a Directory Tree and Recursive Directory Traversal in Python: Make a list of your movies!, but we'll tweak it a bit and build upon it in part two. If you have had the experience of "losing" a file in your system where you don't remember its location and are not even sure of its name, though you remember its type, this is where you might find this recipe useful.

The following is a simple/basic recipe to assist with finding certain files on your system by file extension. If you are looking to utilize Python to manipulate your directory tree or files on your system, there are many tools to help, including Python's standard os module. Last Updated: Wednesday 29 th December 2021
