Hello in this tutorial, we will understand the os.walk method to list the files in a directory using the python programming.
os.walk(……) method will generate the file names in a directory tree by walking the tree either top-down or bottom-up. Represented with the following syntax –
path_namedenotes the directory path which is to be scanned
topdownis an optional argument. If the argument is set to true or unspecified the directories are scanned from top-down. If the argument is set to false the directories are scanned from bottom-top
onerroris an optional argument which shows an error to continue to walk or raise an exception to abort the walk
followlinksis an optional argument which is set to true visits the directories pointed by the symlinks
1.1 Setting up Python
2. Python List files in directory Example
I am using JetBrains PyCharm as my preferred IDE. You are free to choose the IDE of their choice.
2.1 Using the os module
Let us understand this with the help of a code snippet.
Using the os module
If everything goes well the following output will be shown in the IDE console.
That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!
In this tutorial, we learned –
- An introduction to
osmodule in the python programming to list the files in the directory
- Sample program to understand the
You can download the source code of this tutorial from the Downloads section.
This was an example to list the files in the directory using the python programming.
You can download the full source code of this example here: Python os.walk() Method