Python

How to list all files in a directory with Python

April 13, 2022

How to list all files in a directory with Python

In this article we will learn  how to list all the files in a directory with Python – so we can check which files exist or add to a list.

list all files in a directory with Python thumb

Hey you programmer, ok? Let’s learn more about working on directories and files with Python!

We can use a strategy with the listdir module, going through all the items found and checking with the isfile module if it is a file

See the example strategy:

from os import listdir
from os.path import isfile, join

path = 'test'

files = [f for f in listdir(path) if isfile(join(path, f))]

print(files)

In this way we define a directory to check in the path variable, the files will be stored in a list in the files variable

Notice that we created a for to go through all the items in path, which is our path to the folder to check the files

Then we check if it is a file with an isfile, if so, we store the file in files

And then we display the result with a print, in the files variable

Another strategy that we can approach is using the walk module, check it out:

from os import walk

files = []

path = 'test'

for (dirpath, dirnames, filenames) in walk(path):
 files.extend(filenames)
 break

print(files)

Practically the same as the first approach, but we used the walk module this time and create a for to house the files in files

Finally we print the files with a print instruction

Conclusion

In this article we learned how to list all the files in a directory with Python

We use the listdir module for this, in addition to the isfile to verify if the item found is really a file

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x