Home

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

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