本文介绍了Python-使用zipfile读取受密码保护的Word文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to read a password protected word document on Python using zipfile.The following code works with a non-password protected document, but gives an error when used with a password protected file.

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()时,出现以下错误:

When running get_docx_text() with a password protected file, I received the following error:

回溯(最近通话最近一次):

Traceback (most recent call last):

  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

有人对这个代码起作用有任何建议吗?

Does anyone have any advice to get this code to work?

感谢您分享您的知识和专业知识.

Thank you for sharing your knowledge and expertise.

推荐答案

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

I don't think this is an encryption problem, for two reasons:

  1. 在创建ZipFile对象时不尝试解密.诸如 ZipFile.extractall extractopenread使用包含密码的可选pwd参数,但对象构造函数/初始值设定项没有.

  1. Decryption is not attempted when the ZipFile object is created. Methods like ZipFile.extractall, extract, and open, and read take an optional pwd parameter containing the password, but the object constructor / initializer does not.

您的堆栈跟踪表明在创建ZipFile对象时,正在调用setpassword之前的 中,正在引发BadZipFile:

Your stack trace indicates that the BadZipFile is being raised when you create the ZipFile object, before you call setpassword:

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

我会仔细检查正在测试的两个文件之间的其他差异:所有权,权限,安全性上下文(如果您的操作系统上有),...甚至文件名差异也可能导致框架看不到您正在处理的文件.

I'd look carefully for other differences between the two files you're testing: ownership, permissions, security context (if you have that on your OS), ... even filename differences can cause a framework to "not see" the file you're working on.

也---很明显的一个---尝试使用与zip兼容的命令打开加密的zip文件.看看它是否真的是 压缩文件.

Also --- the obvious one --- try opening the encrypted zip file with your zip-compatible command of choice. See if it really is a zip file.

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

I tested this by opening an encrypted zip file in Python 3.1, while "forgetting" to provide a password. I could create the ZipFile object (the variable zfile below) without any error, but got a RuntimeError --- not a BadZipFile exception --- when I tried to read a file without providing a password:

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"扩展名.这两个测试文件产生了相同的堆栈跟踪,一直到行号.

I was also able to raise a BadZipfile exception, once by trying to open an empty file and once by trying to open some random logfile text that I'd renamed to a ".zip" extension. The two test files produced identical stack traces, down to the line numbers.

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,而3.2之前的小f"拼写是BadZipfile- -但是它们之间的距离足够近,我认为这是您要解决的问题.

While this stack trace isn't exactly the same as yours --- mine has a call to _GetContents, and the pre-3.2 "small f" spelling of BadZipfile --- but they're close enough that I think this is the kind of problem you're dealing with.

这篇关于Python-使用zipfile读取受密码保护的Word文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:46
查看更多