【问题标题】:Configurations from file for python dictionaries and stringspython字典和字符串的文件配置
【发布时间】:2015-04-08 06:53:35
【问题描述】:

我有 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 文件,其文本与 config.xml 中的文本相同。然后将新的 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等。

【问题讨论】:

    标签: python dictionary configuration


    【解决方案1】:

    我想只使用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',''))
    

    或者甚至直接导入文件而不复制它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-13
      • 1970-01-01
      • 2019-05-02
      相关资源
      最近更新 更多