【问题标题】:How to export dictionary as a .property file in python如何在 python 中将字典导出为 .property 文件
【发布时间】:2023-01-20 21:47:02
【问题描述】:

如何将 python 中的字典导出到 python 中的 .properties 文件类型?

一个非常简单的可重现的例子,每个人都可以理解

我拥有的:

dict = {"key1":"sentence1", "key2":"sentence2"}

objedt“dict”应该在 python 中保存为 .properties 文件,输出应该如下所示:

key1=sentence1
key2=sentence2

【问题讨论】:

    标签: python dictionary properties-file


    【解决方案1】:

    尝试这个:

    my_dictionary={"key1":"sentence1",  "key2":"sentence2"}
    with open("filename.property", "w") as file:
        list_items=my_dictionary.items()
        for item in list_items:
            file.write(f"{item[0]}={item[1]}
    ")
    

    【讨论】:

    • 谢谢,这就是我需要的。一旦允许我(时间限制),我会接受答案
    【解决方案2】:

    你可以使用 python 内置库configparser

    import configparser
    
    dict = {"key1":"sentence1",  "key2":"sentence2"}
    
    config = configparser.ConfigParser()
    
    # some your default section
    section_name = "default"
    config.add_section(section_name)
    
    for (k, v) in dict.items():
        config.set(section_name, k, v)
    
    with open("config.properties", "w") as f:
        config.write(f)
    

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2016-10-31
      • 2021-12-18
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      相关资源
      最近更新 更多