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
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)
Output:
{'BRAVO': 'BRAVO file',
'alfa': 'alfa file',
'charlie': 'charlie file',
'delta': 'delta file',
'echo': 'echo file',
'fOxtrOt': 'fOxtrOt file',
'golf': 'golf file',
'hotel': 'hotel file'}
-- end of line --