代码之家  ›  专栏  ›  技术社区  ›  sf8193

tomli-w,从python脚本添加数组

  •  1
  • sf8193  · 技术社区  · 2 年前

    我有一个像这样的toml文件

    [[fruits]]
    fruit_property =x
    
    [[fruits]]
    fruit_property =x
    
    [[fruits]]
    fruit_property =x
    

    我想用python脚本对其进行编码。到目前为止,我已经在python中完成了

    fruits= [
     {'fruit_property':x},{'fruit_property':y},  {'fruit_property':z}, 
    ]
    
    toml_string = tomli_w.dumps(fruits)
    

    然后将字符串写入文件。然而,这并没有转换dict数组,而是将它们保持为与代码相同的方式。我已经看过了,但找不到任何文档,有人遇到过类似的问题吗?

    但是,这不会转换

    1 回复  |  直到 2 年前
        1
  •  0
  •   Timeless    2 年前

    看起来像 程序错误 在里面 tomli-w (即使添加了外层 "fruits" 键)。

    我建议你 dumps 你的水果对象 tomlkit ( !pip install tomlkit ):

    import tomlkit
    
    fruits = [
        {"fruit_property": "x"}, {"fruit_property": "y"}, {"fruit_property": "z"},
    ]
    
    toml_string = tomlkit.dumps({"fruits": fruits})
    

    输出:

    print(toml_string)
    
    [[fruits]]
    fruit_property = "x"
    
    [[fruits]]
    fruit_property = "y"
    
    [[fruits]]
    fruit_property = "z"