Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python env with dictionary
#2
I am not too sure what you want to do. I don't know what a .env file is. Your logging variable looks like a .json file.

import json
from pathlib import Path

# don't save in /usr/log, I will use my /home/pedro/temp/ folder
path2json = Path('/home/pedro/temp/log_dict.json')
path2log = Path('/home/pedro/temp/log/')

logging = {
    'module1': {
        'path': '/usr/log/module1.log',
        'level': 'DEBUG'
    },
    'module2': {
        'path': '/usr/log/module2.log',
        'level': 'DEBUG'
    },
    'module3': {
        'path': '/usr/log/module3.log',
        'level': 'DEBUG'
    }
}

# save the logging as json
with open(path2json, 'w', encoding='utf-8') as fp:
    json.dump(logging, fp, ensure_ascii=False, indent=4)

# open the data to inspect it
with open(path2json) as fp:
    data_dict = json.load(fp)
    type(data) # returns <class 'dict'> so we have a Python dictionary

# I won't make files in /usr that could cause problems
# create the log files in /home/pedro/temp/log/
for key in data_dict.keys():
    print(key)
    print(f'path = {data_dict[key]["path"]}')
    logfile = Path(data_dict[key]["path"])
    savename = logfile.name
    savepath = path2log / savename
    with open(savepath, 'a') as sp:
        sp.write(f'This is {logfile}')

# make a list of the files now in path2log
file_list = [filename for filename in path2log.iterdir() if filename.is_file()]

for filename in file_list:
    print(filename)
Now I have 3 log files in /home/pedro/temp/log/:

Output:
/home/pedro/temp/log/module1.log /home/pedro/temp/log/module3.log /home/pedro/temp/log/module2.log
Maybe that is something like what you want?
Reply


Messages In This Thread
python env with dictionary - by maiya - Mar-15-2025, 08:07 AM
RE: python env with dictionary - by Pedroski55 - Mar-16-2025, 10:18 AM
RE: python env with dictionary - by EmilyJohnson - Mar-22-2025, 02:07 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Convert List of Dictionary to dictionary of dictionary list in python kk230689 2 70,207 Apr-27-2019, 03:13 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020