使用zipfile库解压.docx文件

4
我正在尝试编写一个应用程序,从word docx文件中获取表格信息,以便将其转换为pandas DataFrame进行分析。第一步是正确读取docx文件,为此,我正在遵循Virantha Ekanayake的指南Reading and writing Microsoft Word docx files with Python
我在第一步,他们说要使用zipfile库的Zipfile方法将docx文件解压缩为xml文件。我将指南中的函数定义适配到我的代码中(代码如下),但当我运行我的代码时,出现错误提示docx文件“不是zip文件”。
这篇指南中的人说,“实际上,docx文件本质上就是一个zip文件(试着用unzip解压缩它!)……”我已经尝试将docx文件重命名为zip文件,并成功使用WinZip解压缩。然而,在我的程序中,我想能够在不手动将其重命名为.zip文件的情况下解压缩docx文件。我是否能以某种方式在不重命名的情况下解压缩docx文件?或者,如果我必须将其重命名才能使用Zipfile方法,我该如何在我的Python代码中进行此操作?
import zipfile
from lxml import etree
import pandas as pd

FILE_PATH = 'C:/Users/user/Documents/Python Project'

class Application():
    def __init__(self):
        #debug print('Initialized!')
        xml_content = self.get_word_xml(f'{FILE_PATH}/DocxFile.docx') 
        xml_tree = self.get_xml_tree(xml_content)

    def get_word_xml(self, docx_filename):
        with open(docx_filename) as f:
            zip = zipfile.ZipFile(f)
            xml_content = zip.read('word/document.xml')
        return xml_content

    def get_xml_tree(self, xml_string):
        return (etree.fromstring(xml_string))

a = Application()
a.mainloop()

错误:

Traceback (most recent call last):
File "C:\Users\user\Documents\New_Tool.py", line 39, in <module>
a = Application()
File "C:\Users\user\Documents\New_Tool.py", line 27, in __init__
xml_content = self.get_word_xml(f'{FILE_PATH}/DocxFile.docx')
File "C:\Users\user\Documents\New_Tool.py", line 32, in get_word_xml
zip = zipfile.ZipFile(f)
File "C:\Progra~1\Anaconda3\lib\zipfile.py", line 1222, in __init__
self._RealGetContents()
File "C:\Progra~1\Anaconda3\lib\zipfile.py", line 1289, in _RealGetContents
raise BadZipFile("File is not a zip file")
zipfile.BadZipFile: File is not a zip file

zipfile.ZipFile 不关心文件的名称或扩展名,因此问题出在其他地方。 - martineau
1个回答

6

以二进制模式打开文件:

with open(docx_filename, 'rb') as f:

现在完美运行!我是Python的新手,所以忘记了加上读取二进制模式也不奇怪。谢谢! - Maximus3537
对我不起作用。我正在使用最新的Excel版本。 - amol rane
这个讨论是关于docx文件的。Excel与这个讨论有什么关系? - user5386938

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接