如何将Python字典列表以美化格式保存到.txt或.doc文件?
解决方法
写入TXT文件
有两种简单直接的实现方式:
方法1:用pprint.pformat()生成格式化字符串后写入
先把字典列表转换成和终端输出一致的格式化字符串,再写入文件:
import pprint listOfDict = [ {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 34731019, 'yId': 28782454, 'zId': 'dafd'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 48046171, 'yId': 28984154, 'zId': 'mmgj'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 32363003, 'yId': 29164259, 'zId': 'adfa'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 47434038, 'yId': 29164447, 'zId': 'uyti'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 50867569, 'yId': 29165098, 'zId': 'qeqq'}}, {'type': 'myPersonalInfo', 'isPublic': False, 'model': {'xId': 14321214, 'yId': 29271302, 'zId': 'gddf'}} ] # 生成和pprint终端输出一致的字符串 formatted_content = pprint.pformat(listOfDict, sort_dicts=False) # 写入txt文件 with open('formatted_data.txt', 'w', encoding='utf-8') as file: file.write(formatted_content)
方法2:直接重定向pprint输出到文件
让pprint把内容直接写入文件对象,省去字符串转换步骤:
import pprint listOfDict = [ # 你的字典列表内容 ] with open('formatted_data.txt', 'w', encoding='utf-8') as file: pprint.pprint(listOfDict, sort_dicts=False, stream=file)
写入DOC文件
需要借助python-docx库实现,先安装依赖:
pip install python-docx
然后用以下代码写入Word文档:
import pprint from docx import Document from docx.shared import Pt listOfDict = [ # 你的字典列表内容 ] formatted_content = pprint.pformat(listOfDict, sort_dicts=False) # 创建Word文档实例 doc = Document() # 添加格式化内容,可选设置等宽字体提升可读性 paragraph = doc.add_paragraph() run = paragraph.add_run(formatted_content) run.font.name = 'Consolas' run.font.size = Pt(10) # 保存文档 doc.save('formatted_data.docx')
内容的提问来源于stack exchange,提问作者Ashutosh Yadav
相关产品推荐
相关产品推荐

