Python list files in directory

In this post, we will see how to list all files in a directory in Python.

There are multiple ways to list all files in a directory in Python.

Using os.walk

Python os module provides multiple function to get list of files.

List all files in directory and its subdirectories using os.walk(path).
It iterates directory tree in path and for each directory, it returns a tuple with ( ,, )

Output:

/users/apple/temp/sample1.txt
/users/apple/temp/sample2.txt
/users/apple/temp/images/image1.jpeg
/users/apple/temp/images/image2.jpeg

List all .jpeg files in directory and its subdirectories using os.walk(path).

Output:

/users/apple/temp/images/image1.jpeg
/users/apple/temp/images/image2.jpeg

Using os.listdir(path)

You can also use os.listdir(path)to get list of files and subdirectories in a directory. In case, we get subdirectory while iterating, then we call getListOfFiles(path) recursively.

Here is the implementation of recursive function getListOfFiles(path).

Call the above function by passing path.

/users/apple/temp/sample1.txt
/users/apple/temp/sample2.txt
/users/apple/temp/images/image1.jpeg
/users/apple/temp/images/image2.jpeg

Using glob

You can use glob module to list files in directory and its subdirectory. It supports recursive globs using **.
List all files and subdirectories in a directory using glob.glob().

/users/apple/temp/sample1.txt
/users/apple/temp/sample2.txt
/users/apple/temp/images/image1.jpeg
/users/apple/temp/images/image2.jpeg

List all .txt files in directory and its subdirectory

Output:

/users/apple/temp/sample1.txt
/users/apple/temp/sample2.txt

List name of all subdirectories in a directory.

Output:

/users/apple/temp/
/users/apple/temp/images

Conclusion

We have learnt 3 ways to list all files in a directory in Python. We have also learnt about filtering files on the basis of extension.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *