In Python, we may want a list of files or folders in a specified directory. There are several methods that can be used to do this.
os
modulePython’s os
module provides a function that gets a list of files or folders in a directory. The .
, which is passed as an argument to os.listdir()
, signifies the current folder.
import osarr = os.listdir('.')print(arr)
To list files at a specific path, we can simply give the path as a string to the function.
This path will have to be relative to where your Python file is placed or, if you’re not working with files, the path will be relative to where your Python Shell has been launched:
os.listdir('My_Downloads/Music')
glob
moduleThe glob
module also makes it possible to get a list of files or folders in a directory.
import globprint(glob.glob('.'))
We can also print the filenames recursively using the iglob
method. In the method call, the recursive
parameter must be set to True
.
for file_name in glob.iglob('Desktop/**/*.txt', recursive=True):
print(file_name)
The code above will search the Desktop
folder recursively and print all .txt
files. We can replace *.txt
with only a *
to print all files.
The **
command is used to search recursively and is only applicable when the recursive
parameter is True
.
Free Resources