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

Read File From A Single Directory Into A Python Object

This pulls all the files in a given directory into an object with the filename (minus extension) as the key to the content

January 2024
Code
import glob
import os

def load_files(dir):
  files = {}

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

  for path in paths: 
    basename = os.path.basename(path).split('.')[0]
    with open(path) as _in:
      files[basename] = _in.read()

  return files


######################

from pprint import pprint

if __name__ == "__main__":
  source_dir = 'glob_test'
  data = load_files(source_dir)
  pprint(data)
Results
{'BRAVO': 'BRAVO file',
 'alfa': 'alfa file',
 'charlie': 'charlie file',
 'delta': 'delta file',
 'echo': 'echo file',
 'fOxtrOt': 'fOxtrOt file',
 'golf': 'golf file',
 'hotel': 'hotel file'}
═══ § ═══