Programmatically Capturing Filenames

This note demonstrates one way of getting a list of all files in a directory so they can be opened or otherwise used later on.

from os import walk

Get List of All Files and their Folders

In the example below, the directory with the files of interest is called sample-files.

sample_file_list = []
for (dirpath, dirnames, filenames) in walk('.'):
    if dirpath == './sample-files':
        sample_file_list.extend(filenames)
sample_file_list
['Book1.xlsx', 'abc.csv', 'sample_1.txt']

Compare to List Provided by the Shell

%%bash
cd sample-files
ls
Book1.xlsx
abc.csv
sample_1.txt