简体   繁体   English

使用换行符将字典写入文本文件

[英]Write dictionary to text file with newline

I have a python dictionary {'A': '1', 'B': '2', 'C': '3'} .我有一个 python 字典{'A': '1', 'B': '2', 'C': '3'} I want to write this dictionary into a file.我想将此字典写入文件。 This is how I did it;我就是这样做的;

test_dict = {'A': '1', 'B': '2', 'C': '3'}
f = open("dict.txt", "w")
f.write(str(test_dict))
f.close()

However, what I want the text file is to look like this;但是,我希望文本文件看起来像这样;

{
'A': '1', 
'B': '2', 
'C': '3',
}

How do I add the newline when writing to the text file?写入文本文件时如何添加换行符? I am using python 3.7我正在使用 python 3.7

The str () method for a dict return it as a single line print, so if you want to format your output, iterate over the dict and write in the file the way you want. dict 的str ()方法将其作为单行打印返回,因此,如果要格式化 output,请遍历 dict 并以您想要的方式写入文件。

test_dict = {'A': '1', 'B': '2', 'C': '3'}
f = open("dict.txt", "w")
f.write("{\n")
for k in test_dict.keys():
    f.write("'{}':'{}'\n".format(k, test_dict[k]))
f.write("}")
f.close()

This method uses F-string which results in more readable code.此方法使用 F 字符串,这会产生更具可读性的代码。 F-string is supported in python v3, not v2 python v3 支持 F 字符串,不支持 v2

f = open("dict.txt", "w")
f.write("{\n")
    for k in test_dict.keys():        
        f.write(F"'{k}': '{test_dict[k]}',\n")  # add comma at end of line
    f.write("}")
    f.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM