是否有一个Python包可以读取ms office文件的基础xml?

问题描述

我想用python读取PPTX文件的XML,基本上将字符串/数据结构保存到变量中。

我还没有找到可以让我使用Python进行操作的软件包。

解决方法

如果我的理解正确,则可以使用内置的zipfile模块。

import zipfile
archive = zipfile.ZipFile('<My Powerpoint Name>.pptx','r')
xml_file = archive.open('[Content_Types].xml')
text = xml_file.read()
print(text)

这将直接从存档中的[Content_Types].xml打印出xml文本。

如果要解析XML,可以使用内置的xml模块。

import zipfile
import xml.etree.ElementTree as ET

archive = zipfile.ZipFile('<My Powerpoint Name>.pptx','r')
xml_file = archive.open('[Content_Types].xml')
text = xml_file.read()

root = ET.fromstring(text)
value_to_find = r'application/vnd.openxmlformats-package.relationships+xml'
for child in root:
    if child.attrib['ContentType'] == value_to_find:
        print(child.attrib)