繁体   English   中英

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

[英]Reading password protected Word Documents with zipfile

我正在尝试使用 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 object 时不会尝试解密。 ZipFile.extractallextractopen以及read等方法采用包含密码的可选pwd参数,但 object 构造函数/初始化程序没有。

  2. 您的堆栈跟踪表明在您调用setpassword之前创建ZipFile BadZipFile时正在引发 BadZipFile :

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

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

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

我通过在 Python 3.1 中打开一个加密的 zip 文件来测试这个,同时“忘记”提供密码。 我可以创建ZipFile object(下面的变量zfile )而没有任何错误,但是当我尝试在不提供密码的情况下读取文件时出现RuntimeError ---而不是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的调用,以及BadZipfile的 3.2 之前的“small f”拼写——但它们足够接近,我认为这就是那种你正在处理的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM