The Python os.listdir() method within the os module takes a directory as argument and returns a list of all files and directories within the given directory.
Let us explore this method by creating a repl and opening a Python file.
Now let us create a Python program in it:
To support your understanding this is how our setup looks:
In the program above, we first import the “os” module in Python. Then we obtain the current working directory (cwd) using the getcwd() command and save it in the variable called “directory”. Note that the output of this command will be different in different environments. Then we call our os.listdir() method with the current directory (that was just determined). The output of the listdir() method is a list which can be manipulated using any Python list manipulation function. The output is printed using the “print(files)” command.
The output in our case is:
There are several items of interest here. First note that the line printing the current working directory (cwd) will be different in your case so do not fret if the output is not exactly the same. The second line prints the files. As you can see the files such as “main.py” (where the above program is stored), “poetry.lock” and “pyproject.toml” are what you see in the screenshot above. Beyond this you can see a lot of files beginning with a “dot”, and this is why we do not see them in the screenshot above. Nevertheless these files are present in the project. You can click on “Show hidden files” as shown below:
This will reveal the following:
Now you can see the files that were missing. Note that some of them are actually directories (like .config and .upm).
Using os.listdir() to pretty print all files in a directory
Because the output of os.listdir() is a list you can pretty print this list as you see fit. For instance consider the program:
The output is:
Using os.listdir() to print all hidden files
You can take the output of os.listdir() and print all hidden files and directories (i.e., files beginning with a “dot”):
The output is:
In this blogpost, we have seen how Python’s os.listdir() function can help explore directories from within your Python program. If you liked this, checkout our blogpost on the Python os.mkdir() function which as you can surmise helps create directories! Also checkout the Python os.join.path() function which can help create long directory paths.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.