将嵌套字典写入 .txt 文件
将嵌套字典写入 .txt 文件
这个问题已经有了答案:
我有一个像这样的字典
{'Berlin': {'Type1': 96}, 'Frankfurt': {'Type1': 48}, 'London': {'Type1': 288, 'Type2': 64, 'Type3': 426}, 'Paris': {'Type1': 48, 'Type2': 96}}
然后我想要以这个格式写入到.txt文件中
London Type1: 288 Type2: 64 Type3: 426 Paris Type1: 48 Type2: 96 Frankfurt Type1: 48 Berlin Type1: 98
我已经尝试使用
f = open("C:\\Users\\me\\Desktop\\capacity_report.txt", "w+") f.write(json.dumps(mydict, indent=4, sort_keys=True))
但是这样打印出来的格式是这样的:
{ "London": { "Type1": 288, "Type2": 64, "Type3": 426 }, "Paris": { "Type1": 48, "Type2": 96 }, "Frankfurt": { "Type1": 48 }, "Berlin": { "Type1": 98 } }
我想要去掉标点符号和括号。有一种我看不到的方法吗?
admin 更改状态以发布 2023年5月21日
你需要手动编写你的字典。你不是在尝试产生JSON,使用那个模块没有意义。
迭代字典的键和值,将它们作为行写出来。这里的print()
函数可能会有帮助:
from __future__ import print_function with open("C:\\Users\\me\\Desktop\\capacity_report.txt", "w") as f: for key, nested in sorted(mydict.items()): print(key, file=f) for subkey, value in sorted(nested.items()): print(' {}: {}'.format(subkey, value), file=f) print(file=f)
print()
函数会为我们处理换行符。