写字典到txt文件,可以用任何格式对其进行格式化吗?

时间:2019-02-20 14:59:07

标签: python dictionary text

我写了一个小函数来用Python提取字典并将其转换为txt文件。

def dict_to_txt(dict, name):
    dict = {'dict': dict}

    with open('{}.txt'.format(name), 'w') as file:
        file.write(json.dumps(dict))

我的输出如下:

{"dict": {"A": "America", "B": NaN, "C": "?", "D": NaN}}

有什么办法可以输出这样的格式化字典:

{"dict": {"A": "America", 
          "B": NaN, 
          "C": "?", 
          "D": NaN 
 }
}

或某些变化。为了给您一些背景信息,我有一个包含字典的列表,并且正在通过遍历列表来应用此功能。

1 个答案:

答案 0 :(得分:2)

def dict_to_txt(dict, name):
    dict = {'dict': dict}

    with open('{}.txt'.format(name), 'w') as file:
        file.write(json.dumps(dict), indent=2)