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 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 os arr = 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:
glob module also makes it possible to get a list of files or folders in a directory.
import glob print(glob.glob('.'))
We can also print the filenames recursively using the
iglob method. In the method call, the
recursive parameter must be set to
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.
** command is used to search recursively and is only applicable when the
recursive parameter is
View all Courses