Skip to main content
 首页 » 编程设计

python之使用 zipfile 读取受密码保护的 Word 文档

2025年05月04日12lyhabc

我正在尝试使用 zipfile 在 Python 上读取受密码保护的 word 文档。 以下代码适用于不受密码保护的文档,但在使用受密码保护的文件时会出错。

try: 
    from xml.etree.cElementTree import XML 
except ImportError: 
    from xml.etree.ElementTree import XML 
import zipfile 
 
psw = "1234" 
 
WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}' 
PARA = WORD_NAMESPACE + 'p' 
TEXT = WORD_NAMESPACE + 't' 
 
def get_docx_text(path): 
 
    document = zipfile.ZipFile(path, "r") 
    document.setpassword(psw) 
    document.extractall() 
    xml_content = document.read('word/document.xml') 
    document.close() 
    tree = XML(xml_content) 
 
    paragraphs = [] 
    for paragraph in tree.getiterator(PARA): 
        texts = [node.text 
                 for node in paragraph.getiterator(TEXT) 
                 if node.text] 
        if texts: 
            paragraphs.append(''.join(texts)) 
 
    return '\n\n'.join(paragraphs) 

当使用受密码保护的文件运行 get_docx_text() 时,我收到以下错误:

追溯(最近的调用最后):

  File "<ipython-input-15-d2783899bfe5>", line 1, in <module> 
runfile('/Users/username/Workspace/Python/docx2txt.py', wdir='/Users/username/Workspace/Python') 
 
  File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 680, in runfile 
execfile(filename, namespace) 
 
  File "/Applications/Spyder-Py2.app/Contents/Resources/lib/python2.7/spyderlib/widgets/externalshell/sitecustomize.py", line 78, in execfile 
builtins.execfile(filename, *where) 
 
  File "/Users/username/Workspace/Python/docx2txt.py", line 41, in <module> 
x = get_docx_text("/Users/username/Desktop/file.docx") 
 
  File "/Users/username/Workspace/Python/docx2txt.py", line 23, in get_docx_text 
document = zipfile.ZipFile(path, "r") 
 
  File "zipfile.pyc", line 770, in __init__ 
 
  File "zipfile.pyc", line 811, in _RealGetContents 
 
BadZipfile: File is not a zip file 

有没有人有任何建议让这段代码工作?

请您参考如下方法:

我不认为这是一个加密问题,原因有二:

  1. 创建 ZipFile 对象时不尝试解密。类似 ZipFile.extractall 的方法, extract, and open, and read 接受一个包含密码的可选的 pwd 参数,但是对象构造函数/初始化程序没有。

  2. 您的堆栈跟踪表明 BadZipFile 在您创建 ZipFile 对象时被引发,在您调用 设置密码:

    document = zipfile.ZipFile(path, "r") 

我会仔细查看您正在测试的两个文件之间的其他差异:所有权、权限、安全上下文(如果您的操作系统上有这些)……甚至文件名差异也会导致框架“看不到” "您正在处理的文件。

另外 --- 显而易见的 --- 尝试使用您选择的与 zip 兼容的命令打开加密的 zip 文件。查看它是否真的是 压缩文件。

我通过在 Python 3.1 中打开一个加密的 zip 文件来测试这个,同时“忘记”提供密码。我可以创建 ZipFile 对象(下面的变量 zfile)而没有任何错误,但是得到了一个 RuntimeError --- not BadZipFile 异常 --- 当我试图在不提供密码的情况下读取文件时:

Traceback (most recent call last): 
  File "./zf.py", line 35, in <module> 
    main() 
  File "./zf.py", line 29, in main 
    print_checksums(zipfile_name) 
  File "./zf.py", line 22, in print_checksums 
    for checksum in checksum_contents(zipfile_name): 
  File "./zf.py", line 13, in checksum_contents 
    inner_file = zfile.open(inner_filename, "r") 
  File "/usr/lib64/python3.1/zipfile.py", line 903, in open 
    "password required for extraction" % name) 
RuntimeError: File apache.log is encrypted, password required for extraction 

我还能够引发 BadZipfile 异常,一次是通过尝试打开一个空文件,一次是通过尝试打开一些我重命名为“.zip”扩展名的随机日志文件文本.这两个测试文件产生了相同的堆栈跟踪,包括行号。

Traceback (most recent call last): 
  File "./zf.py", line 35, in <module> 
    main() 
  File "./zf.py", line 29, in main 
    print_checksums(zipfile_name) 
  File "./zf.py", line 22, in print_checksums 
    for checksum in checksum_contents(zipfile_name): 
  File "./zf.py", line 10, in checksum_contents 
    zfile = zipfile.ZipFile(zipfile_name, "r") 
  File "/usr/lib64/python3.1/zipfile.py", line 706, in __init__ 
    self._GetContents() 
  File "/usr/lib64/python3.1/zipfile.py", line 726, in _GetContents 
    self._RealGetContents() 
  File "/usr/lib64/python3.1/zipfile.py", line 738, in _RealGetContents 
    raise BadZipfile("File is not a zip file") 
zipfile.BadZipfile: File is not a zip file 

虽然此堆栈跟踪与您的堆栈跟踪不完全相同 --- 我的调用了 _GetContents,并且 pre-3.2 的“small f”拼写BadZipfile --- 但它们非常接近,我认为这就是您要处理的问题。