使用tomli-w从Python生成TOML数组表格式失败的问题求助
生成TOML数组表格式的Python解决方案
你想要生成的TOML数组表格式如下:
[[fruits]] fruit_property = x [[fruits]] fruit_property = y [[fruits]] fruit_property = z
你当前的问题在于:直接用tomli_w.dumps()处理字典列表,得到的是普通TOML数组,而非目标的数组表格式。这是因为tomli_w对TOML结构的映射规则——数组表[[table]]需要对应Python中以表名为键、字典列表为值的字典结构,而非单独的列表。
修改后的代码如下:
import tomli_w # 注意:如果x/y/z是字符串类型,需要添加引号;如果是变量需提前定义 fruits = [ {'fruit_property': 'x'}, {'fruit_property': 'y'}, {'fruit_property': 'z'}, ] # 将列表嵌套在字典中,键名对应TOML的数组表名 toml_data = {'fruits': fruits} toml_string = tomli_w.dumps(toml_data) # 写入文件 with open('output.toml', 'w') as f: f.write(toml_string)
关键说明:
- TOML的
[[fruits]]属于数组表,用于表示同类型表的集合,必须通过Python字典的键值对来映射 - 直接dump单独的列表,tomli_w会生成普通TOML数组(格式为
[{fruit_property = x}, ...]),无法触发数组表的生成规则 - 只有将列表包裹在字典中,让tomli_w识别出键对应的是数组表名称,才能生成你需要的
[[fruits]]格式
内容的提问来源于stack exchange,提问作者sf8193
相关产品推荐
相关产品推荐

