This tutorial shows how to list files with an extension in a directory and its subdirectories. This is an example directory which consists of files and directories.
Using a working directory
If you want to use the working directory, instead of the specified one, you can use the following code.
List all files and directories in the directory non-recursively
This code will get all filenames + extensions and directories from the directory without entering other directories that are inside this one.
And this is the output:
It may be useful if you want to create a program that will print the current directory tree. If you write such a script, you can then convert it to a single exe file.
List only files in the directory non-recursively
In the previous example, both, files and directories are listed.
Let’s display only files.
List all files recursively (directory and subdirectories)
In order to list all files in the directory and it’s subdirectories we will use os.walk. It will check each directory recursively and display all files.
List all files and directories recursively (directory and subdirectories)
List all files recursively using a wildcard and display the full path
So far, we were displaying only files and directories names. This time let’s display the full path. The wildcard (*.*) means that it displays all types of files.
List all files recursively with a specific type of file
You can also display only one type of file. Let’s display only text files. Change (*.*) to (*.txt).
And this is the output.
List all files and directories recursively and display the full path
Only a slight modification (*.* >> *) in the script to display both files and directories.