Sometimes, we want to iterate over files in a given directory with Python.
In this article, we’ll look at how to iterate over files in a given directory with Python.
How to iterate over files in a given directory with Python?
To iterate over files in a given directory with Python, we can use the os.listdir
method.
For instance, we write
import os
directory = os.fsencode(directory_in_str)
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith('.asm') or filename.endswith('.py'):
print(os.path.join(directory, filename))
to call os.list
to list the items in the directory.
Then we call os.path.join
in the loop to join the directory
and filename
into the full path of the file path being iterated through.
Conclusion
To iterate over files in a given directory with Python, we can use the os.listdir
method.