There are many ways you can go about listing files and subfolders within a directory with Python. In this post, we’ll be looking at two commonly used solutions: the listdir() function from the os module and the glob function from the glob module. So, without further ado, let’s get started.
Method 1: The os.listdir() function
Given a path, this function will list the names of all the files and directories in that path. Keep in mind that the returned list does not include the special entries '.'
and '..'
:
"""
This is an example of a directory:
/dir1
/dir2
file1
file2
"""
import os
# the path is the current directory
lst = os.listdir('.')
print(lst)
# ['dir1', 'file2.txt', 'file1.txt', 'dir2']
Method 2: The glob.glob() function:
The glob()
function from the glob
module also returns a list of the names of all files and subfolders in a directory:
import glob
# use the asterisk (*) wildcard to select everything in the current directory
lst = glob.glob('*')
print(lst)
# ['dir1', 'file2.txt', 'file1.txt', 'dir2']
That’s all for this post. Till the next one 🙂