Python中如何将已生成的XML变量写入保存为XML格式文件
解决方法
你已经通过dict2xml生成了格式正常的XML字符串,仅需补充文件写入逻辑即可完成保存,示例完整代码如下:
from dict2xml import dict2xml # 替换为你自己的字典数据 my_dictionary = { "root": { "name": "测试数据", "value": 123 } } xml = dict2xml(my_dictionary) print(xml) # 写入到XML文件 with open("output.xml", "w", encoding="utf-8") as file: file.write(xml)
注意事项
- 写入时指定
encoding="utf-8"可避免XML包含中文等非ASCII字符时出现乱码 - 你可以将代码中的
output.xml替换为自定义的保存路径和文件名 - 如果你需要添加标准XML声明头,可调整写入部分的代码:
with open("output.xml", "w", encoding="utf-8") as file: # 先写入XML声明 file.write('<?xml version="1.0" encoding="UTF-8"?>\n') file.write(xml)
内容的提问来源于stack exchange,提问作者user12217822
相关产品推荐
相关产品推荐

