python 练习0017

版权声明:喜欢就点个赞吧,有啥疑问可以留言交流~ https://blog.csdn.net/m0_38015368/article/details/89360391

问题

将 第 0014 题中的 student.xls 文件中的内容写到 student.xml 文件中,如
下所示:

<?xml version="1.0" encoding="UTF-8"?>
<root>
<students>
<!-- 
	学生信息表
	"id" : [名字, 数学, 语文, 英文]
-->
{
	"1" : ["张三", 150, 120, 100],
	"2" : ["李四", 90, 99, 95],
	"3" : ["王五", 60, 66, 68]
}
</students>
</root>

代码

import xlrd
import xml.dom.minidom
import json
from html.parser import HTMLParser

def get_xls_data(path):
    workbook = xlrd.open_workbook(path)
    worksheet = workbook.sheets()[0]
    data_dict = {}
    for row in worksheet.get_rows():
        tmp_list = [col.value for col in row]
        data_dict[tmp_list[0]] = tmp_list[1:]
    return data_dict

def make_xml(data, path):
    annotations = '''
    <!-- 
    学生信息表
    "id" : [名字, 数学, 语文, 英文]
    -->
    '''
    # indent 参数设置格式,ensure_ascii 防止编码错误
    content = annotations + (json.dumps(data, indent=4, ensure_ascii=False))
    # print(content)
    # 创建一个空文档
    doc = xml.dom.minidom.Document()
    # 创建根结点
    root = doc.createElement('root')
    # 将根结点添加到文档对象中
    doc.appendChild(root)
    # 创建student 节点
    student = doc.createElement('student')
    # 将 student 节点添加到根结点上
    root.appendChild(student)
    # 创建文本节点,用于显示文本内容
    text = doc.createTextNode(content)
    # 将 text 添加到 student 节点上
    student.appendChild(text)
    # 保存
    with open(path, 'w', encoding='utf-8') as f:
        html_parser = HTMLParser()
        result = html_parser.unescape(doc.toxml())
        # print(result)
        # 不能使用 writexml 会转义
        # doc.writexml(f, indent='\t', newl='\n', encoding='utf-8')
        f.write(result)

if __name__ == '__main__':
    path = './student.xls'
    new_path = 'student.xml'
    data = get_xls_data(path)
    # print(data)
    make_xml(data, new_path)

知识点

xls 相关

  • 写 xls 文件 使用 xlwt
  • 读 xls 文件使用 xlrd
  • 读 xls 文件的步骤
    # 打开 workbook 
    workbook = xlrd.open_workboo(file)
    # 获取要写的某个 worksheet 
    worksheet = workbook.sheets()[0]
    # 获取所有的行 
    rows = worksheet.get_rows()
    # 获取某行某一列的值
    value = rows[0][0].value
    

xml、json 相关

  • 使用 json.dumps(dict) 时,如果 dict 中有中文需要注意编码问题 json.dumps(data, ensure_ascii=False)
  • 打开文件时注意编码: with open(path, 'w', encoding='utf-8') as f
  • xml 详情参考 Python 创建XML

猜你喜欢

转载自blog.csdn.net/m0_38015368/article/details/89360391
今日推荐