home
NOTE: Under Construction - I'm in the middle of upgrading my site and lots of stuff is kinda broken. Please forgive the mess.

Get a list of files from a directory in Python

This is how I get a list of files from a single directory in Python (i.e. it doesn' recurse into sub-directories)

August 2018
Code
import glob
import os

source_dir = 'glob_test'

file_list = [
    file for file in glob.glob(f"{source_dir}/*")
    if os.path.isfile(file)
]

for file in file_list:
    print(file)
Results
glob_test/echo.txt
glob_test/BRAVO.txt
glob_test/fOxtrOt.txt
glob_test/hotel.txt
glob_test/charlie.txt
glob_test/golf.txt
glob_test/delta.txt
glob_test/alfa.txt
  • Is not recursive

  • Does not return directories

  • Does not return hidden files

NOTE that you can use this to get the absolute path:

`os.path.abspath(file) for file in glob.glob(f"{font_dir}/*/*.ttf")`

TODO: Figure out if you want to add that

Old notes

This works to get a list of files recursively:

Code
import glob
from os.path import isfile

source_directory = 'some/path/to/files'

source_files = [
    file for file in glob.glob(
        f"{source_directory}/**/*",
        recursive=True
    )
    if isfile(file)
]

NOTE: Does not pick up . invisible files.

Old Notes

Getting a list of files in python

Glob works:

Code
import glob
    
schedule_files = glob.glob(*.xml)
    
for schedule_file in schedule_files:
    print(schedule_file)

You can also do recursive like this:

Code
file_list = glob.glob(f'{root_path}/**/*.mp3', recursive=True)

TODO: Test with different structures to confirm and provide examples.

Code
#!/usr/bin/env python
    
from os import listdir
from os.path import isfile, join
    
source_dir = 'some-dir'
file_list = [f for f in listdir(source_dir) if isfile(join(source_dir, f))]

This returns the list of filenames including the extension but without the directory path.

This does include files that start with a `.`

Directories ignoring hidden files

Code
#!/usr/bin/env python3

from os import listdir

source_dir = 'designs'
dir_list = [d for d in listdir(source_dir) if d[0] != '.']
print(dir_list)
═══ § ═══

Footnotes And References