List all files with Python
In this article, we will learn how to list all files with Python and in a simple way, using resources from libraries that already exist in the language.
Hey you all programmers, okay? Let’s learn more about Python!
We have two widely used alternatives to list files in Python, the first is using listdir
A native library, which will help us with this function.
Let’s see a practical example:
from os import listdir from os.path import isfile, join path = './' files = [f for f in listdir(path) if isfile(join(path, f))] print(files )
Here we basically import the listdir library, and create a variable for path, which is the path or directory we want to check the files
Then we store a loop that will iterate through all the files in that path, returning us a list with their names, in the files variable
Finally we print the file list
Another well-used way for this purpose is using the walk library of the OS set.
The idea is very similar, let’s see this practical example:
path = './' files =  for (dirpath, dirnames, filenames) in walk(path): files.extend(filenames) break print(files)
We also created variables for the path of the files and one to store their name, which is the files
Then we do the for in the walk function, notice that this way we can extract the directories, not just the files as well.
And finally the result is printed with print method
In this article we learned how to list all files with Python
Using two different methods, which are quite popular, the first method was using the listdir library.
The second was the turn of OS.walk, where we learned that it is also possible to retrieve the name of the actual directories
Want to learn more about Python? Click here!