Search code examples
pythonpasswordswin32comdoc

How can I determine whether a Word document has a password?


I am trying to read word documents using Python. However, I am stuck in places where the document is password protected, as I do not have the password for the file(s).

How can I detect if the file has password, so can I ignore such files from opening?

Currently, the below code opens a dialog/prompt window in MS-Word to enter the password and keeps waiting for a response.

word = win32.gencache.EnsureDispatch('Word.Application')
doc = word.Documents.Open(r"D:\appointment\PasswordProtectedDoc.doc")

Solution

  • Well I figured out the answer myself. Passed a wrong password as a parameter and it raised an exception saying Invalid/Incorrect password which I can handle it in a try except block. Little strange but works well.

    word = win32.gencache.EnsureDispatch('Word.Application')
    word.Visible = False
    try:
        doc = word.Documents.Open(r"D:\appointment\PasswordProtectedDoc.doc",PasswordDocument='ddd')
        doc.Activate ()
    except:
        print(f"Failed to open")
    finally:
        word.Quit()