【问题标题】:Write dictionary to text file with newline使用换行符将字典写入文本文件
【发布时间】:2020-05-19 15:25:30
【问题描述】:

我有一个 python 字典{'A': '1', 'B': '2', 'C': '3'}。我想将此字典写入文件。我就是这样做的;

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

但是,我希望文本文件看起来像这样;

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

写入文本文件时如何添加换行符? 我正在使用 python 3.7

【问题讨论】:

    标签: python python-3.x writefile


    【解决方案1】:

    dict 的 str() 方法将其作为单行打印返回,因此如果要格式化输出,请遍历 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()
    

    【讨论】:

      【解决方案2】:

      此方法使用 F 字符串,从而使代码更具可读性。 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()
      

      【讨论】:

        猜你喜欢
        • 2016-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多