Python 3.x 将dict写入具有特定格式的文件
如果我想用每行的特定格式将dict写入文件,那么最好的方法是什么 目前我正在做:Python 3.x 将dict写入具有特定格式的文件,python-3.x,dictionary,formatting,output,Python 3.x,Dictionary,Formatting,Output,如果我想用每行的特定格式将dict写入文件,那么最好的方法是什么 目前我正在做: with open('filename', 'w') as j: print(dct, file = j) 但正如你所期望的,我的结果是: {<key>: <value>, <key>: <value>, <key>: <value>} {:,:,:} 是否有一种简单的方法来格式化输出,使其读取与以下内容相
with open('filename', 'w') as j:
print(dct, file = j)
但正如你所期望的,我的结果是:
{<key>: <value>, <key>: <value>, <key>: <value>}
{:,:,:}
是否有一种简单的方法来格式化输出,使其读取与以下内容相同的dict:
<key> <value>
<key> <value>
<key> <value>
您可以按如下方式执行:
def write_dict(out_dict, filename):
with open(filename, 'w') as f:
for key, value in out_dict.items():
f.write('{} {}\n'.format(key, value))
你不应该,他们都是天生的。但是您确实需要确保文件可以实际打开(即python的
open
实际上不会沿文件路径为您创建丢失的目录),它只是说dict对象没有属性iteritemswopse,在python 3中它只是项