如何将Python字典格式化为带换行与缩进的字符串并保存至文件?
格式化保存Python字典到文件的简便方法
方法1:用pprint模块(最贴合需求)
Python标准库的pprint就是专门用来美化打印数据结构的,直接输出带层级缩进的格式,完全符合你要的效果。
示例代码:
import pprint meals = { 'chilli': { 'ingredients': {'vegetarian mince': 500, 'tin of tomatoes': 1, 'red onion': 1}, 'prep_time': 1, 'storage_time': 3 } } # 写入文件时指定输出流和缩进宽度 with open('meals.txt', 'w') as f: pprint.pprint(meals, stream=f, indent=4)
生成的文件内容会自动按层级换行、缩进,还能通过width参数控制每行最大长度,避免单行过长。
方法2:用json模块(适合跨语言场景)
如果不需要严格的Python字典格式,JSON格式的可读性也很强,还支持跨语言解析:
import json meals = { 'chilli': { 'ingredients': {'vegetarian mince': 500, 'tin of tomatoes': 1, 'red onion': 1}, 'prep_time': 1, 'storage_time': 3 } } with open('meals.json', 'w') as f: json.dump(meals, f, indent=4, ensure_ascii=False)
indent=4控制缩进宽度,ensure_ascii=False用来保留中文等非ASCII字符。生成的内容是标准JSON(用双引号),但可读性同样优秀。
方法3:手动处理(不推荐)
如果非要自己搞,可以用repr转字符串再配合textwrap调整格式,但繁琐容易出错,只适合特殊场景:
import textwrap meals = { 'chilli': { 'ingredients': {'vegetarian mince': 500, 'tin of tomatoes': 1, 'red onion': 1}, 'prep_time': 1, 'storage_time': 3 } } # 先替换字符实现换行,再添加缩进 dict_str = repr(meals).replace('{', '{\n').replace(', ', ',\n') formatted_str = textwrap.indent(dict_str, ' ') # 加上变量名并修正开头缩进 formatted_str = 'meals = ' + formatted_str[4:] with open('meals.txt', 'w') as f: f.write(formatted_str)
总结
优先用pprint,代码最简单,输出格式完全匹配你的需求;跨语言场景选json;手动处理的方法尽量别用,费事儿还容易出问题。
内容的提问来源于stack exchange,提问作者superdupersolly
相关产品推荐
相关产品推荐

