【问题标题】:Python - When Outputting Dictionary to External Text File Only First Key Is Being OutputtedPython - 将字典输出到外部文本文件时,仅输出第一个键
【发布时间】:2016-09-17 20:46:20
【问题描述】:

我的问题:

我需要将字典中的每个项目输出到 Python 中的外部文本文件。 像下面这样:

dict1 = {}

gen1 = 1
aha = 2

dict1['Generation'] = gen1 
dict1['Population'] = aha

  for key, value in sorted(dict1.items()):
      print(key,':',value, file = open('text.txt', 'w'))

在此示例中,我在字典中有 2 个键,但是当我运行代码并转到文件时,仅输出第一个键的唯一行。

我该怎么做才能将字典中的所有键都打印到外部文件中?

谢谢

【问题讨论】:

    标签: python file python-3.x dictionary printing


    【解决方案1】:

    您在for 循环的每次迭代中都重新打开文件以进行写入(并因此清除它)。使用

    with open('text.txt', 'w') as out:
       for key, value in sorted(dict1.items()):
           print(key,':',value, file=out)
    

    或者,只需将原始代码中的 open('text.txt', 'w') 更改为 open('text.txt', 'a') 即可打开文件进行附加。不过,这比只打开一次文件效率低。

    【讨论】:

    • @John_Sm1 没问题。随意接受解决问题的答案之一。
    【解决方案2】:

    每次调用open('text.txt', 'w') 都会截断文件。这意味着,在写入第二个项目之前,文件将被清除,第一个项目将丢失。

    您应该只打开一次并将其保存在变量中:

    # not final solution yet!
    f = open('text.txt', 'w')
    for key, value in sorted(dict1.items()):
        print(key, ':', value, file=f)
    

    然而在 Python 中,大多数时候你应该使用with statement 来确保文件被正确关闭:

    with open('text.txt', 'w') as f:
        for key, value in sorted(dict1.items()):
            print(key, ':', value, file=f)
    

    【讨论】:

      【解决方案3】:

      您应该使用 json 模块将您的 dict 转储到文件中,而不是重新发明轮子:

      import json
      
      dict1 = {}
      
      gen1 = 1
      aha = 2
      
      dict1['Generation'] = gen1 
      dict1['Population'] = aha
      
      with open('text.txt', 'w') as dict_file:
          json.dump(dict1, dict_file)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-18
        • 2014-07-28
        • 1970-01-01
        • 2020-07-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多