【问题标题】:Writing a dictionary to a textile line by line [duplicate]逐行将字典写入纺织品[重复]
【发布时间】:2019-06-01 13:25:56
【问题描述】:

我有一些代码可以创建字典并将其粘贴到文本文件中。但它将字典粘贴为一行。下面我有代码和它创建的文本文件。

print('Writing to Optimal_System.txt in %s\n' %(os.getcwd()))    
f = open('Optimal_System.txt','w')
f.write(str(optimal_system))
f.close  

有没有办法让文本文件像这样给每个键值对赋予它自己的行?

{'Optimal Temperature (K)': 425
 'Optimal Pressure (kPa)': 100
 ...
}

【问题讨论】:

  • 正如重复目标所暗示的,使用json 模块来执行此操作。
  • 遍历yourdictionary.items()的键值对;使用string formatting 从每个键/值构造一行(带有换行符);将行写入文件。

标签: python


【解决方案1】:

使用格式化字符串并假设optimal_system 是您的字典:

with open('output.txt', 'w') as f:
    for k in optimal_system.keys():
        f.write("{}: {}\n".format(k, optimal_system[k]))

编辑

正如@wwii所指出的,上面的代码也可以写成:

with open('output.txt', 'w') as f:
    for k, v in optimal_system.items():
        f.write("{}: {}\n".format(k, v))

字符串可以使用formatted string literals 格式化,自python 3.6 起可用,因此f'{k}: {v}\n' 而不是"{}: {}\n".format(k, v)

【讨论】:

  • for k,v in optimal_system.items(): ... .format(k,v)...。对于 Python 3.6,该行可以使用 f-string - f'{k}: {v}\n
  • @wwii 我会在答案中添加这个,谢谢!
  • 谢谢,这很好用。只是好奇,我是否应该在 for 循环之外键入“f.close()”以确保其关闭?
  • @bbalzano 与构造 with open('filename', 'w') as f: 调用 f.close() 是不需要的。查看here了解更多详情。
【解决方案2】:

您可以使用pprint module——它也适用于所有其他数据结构。 要强制在新行中输入每个条目,请将 width 参数设置为较低的值。 stream 参数允许您直接写入文件。

import pprint
mydata = {'Optimal Temperature (K)': 425,
          'Optimal Pressure (kPa)': 100,
          'other stuff': [1, 2, ...]}
with open('output.txt', 'w') as f:
    pprint.pprint(mydata, stream=f, width=1)

将产生:

{'Optimal Pressure (kPa)': 100,
 'Optimal Temperature (K)': 425,
 'other stuff': [1,
                 2,
                 Ellipsis]}

【讨论】:

    【解决方案3】:

    您可以使用 json.dumps() 通过 indent 参数执行此操作。例如:

    import json
    
    dictionary_variable = {'employee_01': {'fname': 'John', 'lname': 'Doe'},
                           'employee_02': {'fname': 'Jane', 'lname': 'Doe'}}
    
    with open('output.txt', 'w') as f:
        f.write(json.dumps(dictionary_variable, indent=4))
    

    【讨论】:

      猜你喜欢
      • 2011-10-26
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 2018-08-18
      相关资源
      最近更新 更多