Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

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

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'}