我们如何从 python 中的嵌套目录创建配置文件?

how can we create a config file from a nested directory in python?

我是新手 python,我已经学会了将配置文件数据推送到嵌套字典中。反之亦然? 示例 fille 如下:

我需要

字典 = { 'section1' : { 'name' : 'abcd' , 'language' : 'python' } , 'section2' : { 'name' : 'aaaa' , 'language' : 'java' } }

变成这样

[第 1 节]

姓名:abcd

语言:python

[section2]

姓名:aaaa

语言:java

您的预期输出看起来像一个 toml 输出。尝试:

import toml
toml.dumps(dictonary)

toml - PyPI

这会起作用,原因如下:

our_dict = {
  'section1':{
    'name':'abcd',
    'language':'python'
    },
  'section2':{
  'name':'aaaa',
  'language':'java'
    }
  } 
def dictFunc(dictionary):
  ret = ''
  for i in dictionary:
    value = dictionary.get(i)
    ret += '\n' + i + ':\n'
    for j in value:
      k = value.get(j)
      ret += j + ':' + k + '\n'
  return ret
print(dictFunc(our_dict))

首先,我们声明our_dict。然后,我们用 one argument 声明 function dictFunc()dictionary。我们制作了一个名为 retvariable,我们很快就会将其命名为 return。我们首先循环 dictionary,然后声明 variable value。这是 dictionarysecond-place key(即 {'name':'aaaa','language':'java'})。我们确保将 key(即 section1)添加到 ret。我们循环 second-place key,或 j,得到 jj's current key,或 k(即 name)。最后,我们得到 j's current second-place key,并且 link 它们一起在 ret 中。我们现在 return ret.

您可以使用模块configparser

import configparser

dictonary = {
    'section1' : { 'name' : 'abcd' , 'language' : 'python' } ,
    'section2' : { 'name' : 'aaaa' , 'language' : 'java' } }

config = configparser.RawConfigParser()
for section, pairs in dictonary.items():
    config.add_section(section)
    for k,v in pairs.items():
        config.set(section, k, v)

with open('example.cfg', 'w') as configfile:
    config.write(configfile)