Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

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)

python
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 start

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 :

python
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 [TODO: Code shorthand span ] invisible files.

Old Notes

Getting a list of files in python

Glob works :

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

You can also do recursive like this :

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

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

python
#!/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

python
#!/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