在 Python 中循环导入字典

高拉夫班萨尔

我的问题是与此相关的一个我有一个config_file由字典组成的字典,如下所示:

config_1 = {
    'folder': 'raw1',
    'start_date': '2019-07-01'
}
config_2 = {
    'folder': 'raw2',
    'start_date': '2019-08-01'
}
config_3 = {
    'folder': 'raw3',
    'start_date': '2019-09-01'
}

然后我有一个单独的 python 文件,它导入每个配置并执行一些操作:

from config_file import config_1 as cfg1
Do some stuff using 'folder' and 'start_date'

from config_file import config_2 as cfg2
Do some stuff using 'folder' and 'start_date'

from config_file import config_2 as cfg3
Do some stuff using 'folder' and 'start_date'

我想把它放在一个循环中,而不是在 python 文件中列出 3 次。我怎样才能做到这一点?

马西福克斯

如果我正确理解您的问题,只需使用importlib简而言之,你在 python 中写的是什么:

from package import module as alias_mod

在 importlib 中它变成:

alias_mod = importlib.import_module('module', 'package')

或者,等效地:

alias_mod = importlib.import_module('module.package')

例如:

from numpy import random as rm

在导入库中:

rm = importlib.import_module('random', 'numpy')

另一个有趣的事情是这篇文章中提出的这段代码,它不仅允许您导入模块和包,还可以直接导入函数等:

def import_from(module, name):
    module = __import__(module, fromlist=[name])
    return getattr(module, name)

对于您的具体情况,此代码应该有效:

import importlib

n_conf = 3
for in range(1, n_conf)
    conf = importlib.import_module('config_file.config_'+str(i))
    # todo somethings with conf 

但是,如果我能给你一些建议,我认为对你来说最好的事情是构建一个 json 配置文件并读取该文件而不是导入模块。舒服多了。例如,在您的情况下,您可以创建这样的config.json文件:

{
    "config_1": {
        "folder": "raw1",
        'start_date': '2019-07-01'
    },
    "config_2": {
        'folder': 'raw2',
        'start_date': '2019-08-01'
    },
    "config_3": {
        'folder': 'raw3',
        'start_date': '2019-09-01'
    }
}

读取json文件如下:

import json
with open('config.json') as json_data_file:
    conf = json.load(json_data_file)

现在您在内存中有一个简单的 Python 字典,其中包含您感兴趣的配置设置:

conf['config_1']
# output: {'folder': 'raw1', 'start_date': '2019-07-01'}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章