Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 写一本字典到txt文件,有没有格式化的方法?_Python_Dictionary_Text - Fatal编程技术网

Python 写一本字典到txt文件,有没有格式化的方法?

Python 写一本字典到txt文件,有没有格式化的方法?,python,dictionary,text,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}} 有什么方

我编写了一个小函数,用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 
 }
}

或者是这个的一些变体。为了给您提供一些上下文,我有一个包含字典的列表,并通过迭代列表来应用此函数。

看起来像自定义格式任务。哎呀!我明白了-非常简单。。下面编辑如果您使用的是
json.dumps
,它有一个
indent
参数,可以创建缩进输出。它并不完全是您所展示的格式,但它比一行上的方法更具可读性。(而且,依我看,比您在示例中显示的堆叠符号更可读。)看起来像是自定义格式任务。哎呀!我明白了-非常简单。。下面编辑如果您使用的是
json.dumps
,它有一个
indent
参数,可以创建缩进输出。它并不完全是您所展示的格式,但它比一行上的方法更具可读性。(而且,在我看来,它比您在示例中展示的堆叠符号更可读。)它应该是
file.write(json.dumps(dict,indent=2))
它应该是
file.write(json.dumps(dict,indent=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)