python 字典和字符串的文件配置

Configurations from file for python dictionaries and strings

我有 python 脚本的配置,其中包括整数、字符串和字典。示例 config.txt 文件如下

mode = 'train,test,validation'

pick_one_in_n_files = 2

#dictionary for labels
labels = dict(
    bowl=0,
    coffee_mug=1,
    food_bad=2,
    food_box=3,
    food_can=4,
    instant_noodles=5,
    plate=6,
    soda_can=7,
    sponge=8,
    water_bottle=9
    )

我正在阅读此文本文件并编写一个新的临时 python 文件,其文本与配置中的文本相同。然后将新的 python 文件导入我的脚本并使用其中的数据。

configuration_import = open(config_path.replace('txt','py'),mode =       'w+')
configuration_text = open(config_path,mode ='r')
configuration_import.write(configuration_text.read())
configuration_import.close()
configuration_text.close()
return importlib.import_module(config_path.replace('.txt',''))

这达到了目的,但我正在寻找解决此问题的优雅方法。

这样用户将只提供一个配置文本文件。不允许他编辑 python 个文件。缺点是文件必须是 python 格式而不是一些标准的 yaml,json 等

我想只要使用 with 就可以稍微清理一下:

with open(config_path, mode = 'r') as file_in:
    with open(config_path.replace('.txt', '.py'), mode = 'w') as file_out:
        for line in file_in:
            file_out.write(line)
return importlib.import_module(config_path.replace('.txt',''))

甚至根本不复制而直接导入文件。