Automating Comparison of Word Documents Using Python












0















I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:



import win32com.client
Application=win32com.client.gencache.EnsureDispatch("Word.Application")
Document=Application.Documents.Add()
Application.CompareDocuments("Original.docx","Revised.docx")


But I am getting the following error:



Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
Application.CompareDocuments("Original.docx","Revised.docx")

File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
, CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings

File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)

TypeError: The Python instance can not be converted to a COM object


I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.



Thanks in Advance










share|improve this question



























    0















    I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:



    import win32com.client
    Application=win32com.client.gencache.EnsureDispatch("Word.Application")
    Document=Application.Documents.Add()
    Application.CompareDocuments("Original.docx","Revised.docx")


    But I am getting the following error:



    Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
    Application.CompareDocuments("Original.docx","Revised.docx")

    File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
    , CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings

    File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
    return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)

    TypeError: The Python instance can not be converted to a COM object


    I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.



    Thanks in Advance










    share|improve this question

























      0












      0








      0


      1






      I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:



      import win32com.client
      Application=win32com.client.gencache.EnsureDispatch("Word.Application")
      Document=Application.Documents.Add()
      Application.CompareDocuments("Original.docx","Revised.docx")


      But I am getting the following error:



      Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
      Application.CompareDocuments("Original.docx","Revised.docx")

      File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
      , CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings

      File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
      return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)

      TypeError: The Python instance can not be converted to a COM object


      I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.



      Thanks in Advance










      share|improve this question














      I am trying to use win32com(pywin32) and Microsoft Word's Object Model to Compare two Word Documents(Automating the task of Comparing two documents in Microsoft word under Review->Compare). Following is the code I have written for this:



      import win32com.client
      Application=win32com.client.gencache.EnsureDispatch("Word.Application")
      Document=Application.Documents.Add()
      Application.CompareDocuments("Original.docx","Revised.docx")


      But I am getting the following error:



      Traceback (most recent call lastFile "<pyshell#9>", line 1, in <module>
      Application.CompareDocuments("Original.docx","Revised.docx")

      File "C:Python36libsite-packageswin32comgen_py0020905-0000-0000-C000-000000000046x0x8x6_Application.py", line 79, in CompareDocuments
      , CompareFields, CompareComments, CompareMoves, RevisedAuthor, IgnoreAllComparisonWarnings

      File "C:Python36libsite-packageswin32comclient__init__.py", line 466, in _ApplyTypes_
      return self._get_good_object_(self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),user, resultCLSID)

      TypeError: The Python instance can not be converted to a COM object


      I am not able to understand why this error is being thrown. I really want to resolve this issue.Please help.



      Thanks in Advance







      python word-vba pywin32 win32com






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 9 '17 at 22:11









      AngryMan14AngryMan14

      12




      12
























          3 Answers
          3






          active

          oldest

          votes


















          0














          The error is thrown because the arguments you pass in the function Application.CompareDocuments(), being written such as "Original.docx" and "Revised.docx", are not a Document object from the point of view of your python code.



          You need to create these objects with the function Application.Documents.Open()



          A code working for me is:



          import win32com.client

          path = "C:ThePathOfYourFolderWithYourDocuments\"
          # note the \ at the end of the path name to prevent a SyntaxError

          #Create the Application word
          Application=win32com.client.gencache.EnsureDispatch("Word.Application")

          # Compare documents
          Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
          Application.Documents.Open(path + "Revised.docx"))

          # Save the comparison document as "Comparison.docx"
          Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
          # Don't forget to quit your Application
          Application.Quit()


          The you have your Comparison.docx you can open to check.



          Let me know if it works for you.






          share|improve this answer































            0














            Ben. T's answer works. I would include:



            Application.ActiveDocument.ActiveWindow.View.Type = 3


            before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).






            share|improve this answer

































              0














              I created a more versatile version of this with path and file checks, if someone wants it...



              #!/usr/bin/python3
              # This uses win32com to automate the comparison of two Microsoft Word files.
              # Make sure to have win32com installed for your environment and python version:
              # https://github.com/mhammond/pywin32/releases
              # Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python

              from os import getcwd, path
              from sys import argv, exit
              from win32com import client

              def die(message):
              print (message)
              exit(1)

              def cmp(original_file, modified_file):
              dir = getcwd() + '\'
              print('Working...')

              # some file checks
              if not path.exists(dir+original_file):
              die('Original file does not exist')
              if not path.exists(dir+modified_file):
              die('Modified file does not exist')
              cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
              if path.exists(cmp_file):
              die('Comparison file already exists... abortingnRemove or rename '+cmp_file)

              # actual Word automation
              app = client.gencache.EnsureDispatch("Word.Application")
              app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
              app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
              app.ActiveDocument.SaveAs(cmp_file)

              print('Saved comparison as: '+cmp_file)
              app.Quit()

              def main():
              if len(argv) != 3:
              die('Usage: wrd_cmp <original_file> <modified_file>')
              cmp(argv[1], argv[2])

              if __name__ == '__main__':
              main()





              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47212459%2fautomating-comparison-of-word-documents-using-python%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                0














                The error is thrown because the arguments you pass in the function Application.CompareDocuments(), being written such as "Original.docx" and "Revised.docx", are not a Document object from the point of view of your python code.



                You need to create these objects with the function Application.Documents.Open()



                A code working for me is:



                import win32com.client

                path = "C:ThePathOfYourFolderWithYourDocuments\"
                # note the \ at the end of the path name to prevent a SyntaxError

                #Create the Application word
                Application=win32com.client.gencache.EnsureDispatch("Word.Application")

                # Compare documents
                Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
                Application.Documents.Open(path + "Revised.docx"))

                # Save the comparison document as "Comparison.docx"
                Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
                # Don't forget to quit your Application
                Application.Quit()


                The you have your Comparison.docx you can open to check.



                Let me know if it works for you.






                share|improve this answer




























                  0














                  The error is thrown because the arguments you pass in the function Application.CompareDocuments(), being written such as "Original.docx" and "Revised.docx", are not a Document object from the point of view of your python code.



                  You need to create these objects with the function Application.Documents.Open()



                  A code working for me is:



                  import win32com.client

                  path = "C:ThePathOfYourFolderWithYourDocuments\"
                  # note the \ at the end of the path name to prevent a SyntaxError

                  #Create the Application word
                  Application=win32com.client.gencache.EnsureDispatch("Word.Application")

                  # Compare documents
                  Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
                  Application.Documents.Open(path + "Revised.docx"))

                  # Save the comparison document as "Comparison.docx"
                  Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
                  # Don't forget to quit your Application
                  Application.Quit()


                  The you have your Comparison.docx you can open to check.



                  Let me know if it works for you.






                  share|improve this answer


























                    0












                    0








                    0







                    The error is thrown because the arguments you pass in the function Application.CompareDocuments(), being written such as "Original.docx" and "Revised.docx", are not a Document object from the point of view of your python code.



                    You need to create these objects with the function Application.Documents.Open()



                    A code working for me is:



                    import win32com.client

                    path = "C:ThePathOfYourFolderWithYourDocuments\"
                    # note the \ at the end of the path name to prevent a SyntaxError

                    #Create the Application word
                    Application=win32com.client.gencache.EnsureDispatch("Word.Application")

                    # Compare documents
                    Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
                    Application.Documents.Open(path + "Revised.docx"))

                    # Save the comparison document as "Comparison.docx"
                    Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
                    # Don't forget to quit your Application
                    Application.Quit()


                    The you have your Comparison.docx you can open to check.



                    Let me know if it works for you.






                    share|improve this answer













                    The error is thrown because the arguments you pass in the function Application.CompareDocuments(), being written such as "Original.docx" and "Revised.docx", are not a Document object from the point of view of your python code.



                    You need to create these objects with the function Application.Documents.Open()



                    A code working for me is:



                    import win32com.client

                    path = "C:ThePathOfYourFolderWithYourDocuments\"
                    # note the \ at the end of the path name to prevent a SyntaxError

                    #Create the Application word
                    Application=win32com.client.gencache.EnsureDispatch("Word.Application")

                    # Compare documents
                    Application.CompareDocuments(Application.Documents.Open(path + "Original.docx"),
                    Application.Documents.Open(path + "Revised.docx"))

                    # Save the comparison document as "Comparison.docx"
                    Application.ActiveDocument.SaveAs (FileName = path + "Comparison.docx")
                    # Don't forget to quit your Application
                    Application.Quit()


                    The you have your Comparison.docx you can open to check.



                    Let me know if it works for you.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Mar 5 '18 at 16:39









                    Ben.TBen.T

                    6,0272625




                    6,0272625

























                        0














                        Ben. T's answer works. I would include:



                        Application.ActiveDocument.ActiveWindow.View.Type = 3


                        before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).






                        share|improve this answer






























                          0














                          Ben. T's answer works. I would include:



                          Application.ActiveDocument.ActiveWindow.View.Type = 3


                          before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).






                          share|improve this answer




























                            0












                            0








                            0







                            Ben. T's answer works. I would include:



                            Application.ActiveDocument.ActiveWindow.View.Type = 3


                            before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).






                            share|improve this answer















                            Ben. T's answer works. I would include:



                            Application.ActiveDocument.ActiveWindow.View.Type = 3


                            before saving if you like viewing the document in Print Layout. Otherwise the saved Comparison.docx opens as Web Layout by default (Type = 6).







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited Nov 21 '18 at 23:32









                            Fabio Turati

                            2,57652138




                            2,57652138










                            answered Nov 21 '18 at 23:10









                            Zenon AndersonZenon Anderson

                            1




                            1























                                0














                                I created a more versatile version of this with path and file checks, if someone wants it...



                                #!/usr/bin/python3
                                # This uses win32com to automate the comparison of two Microsoft Word files.
                                # Make sure to have win32com installed for your environment and python version:
                                # https://github.com/mhammond/pywin32/releases
                                # Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python

                                from os import getcwd, path
                                from sys import argv, exit
                                from win32com import client

                                def die(message):
                                print (message)
                                exit(1)

                                def cmp(original_file, modified_file):
                                dir = getcwd() + '\'
                                print('Working...')

                                # some file checks
                                if not path.exists(dir+original_file):
                                die('Original file does not exist')
                                if not path.exists(dir+modified_file):
                                die('Modified file does not exist')
                                cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
                                if path.exists(cmp_file):
                                die('Comparison file already exists... abortingnRemove or rename '+cmp_file)

                                # actual Word automation
                                app = client.gencache.EnsureDispatch("Word.Application")
                                app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
                                app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
                                app.ActiveDocument.SaveAs(cmp_file)

                                print('Saved comparison as: '+cmp_file)
                                app.Quit()

                                def main():
                                if len(argv) != 3:
                                die('Usage: wrd_cmp <original_file> <modified_file>')
                                cmp(argv[1], argv[2])

                                if __name__ == '__main__':
                                main()





                                share|improve this answer




























                                  0














                                  I created a more versatile version of this with path and file checks, if someone wants it...



                                  #!/usr/bin/python3
                                  # This uses win32com to automate the comparison of two Microsoft Word files.
                                  # Make sure to have win32com installed for your environment and python version:
                                  # https://github.com/mhammond/pywin32/releases
                                  # Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python

                                  from os import getcwd, path
                                  from sys import argv, exit
                                  from win32com import client

                                  def die(message):
                                  print (message)
                                  exit(1)

                                  def cmp(original_file, modified_file):
                                  dir = getcwd() + '\'
                                  print('Working...')

                                  # some file checks
                                  if not path.exists(dir+original_file):
                                  die('Original file does not exist')
                                  if not path.exists(dir+modified_file):
                                  die('Modified file does not exist')
                                  cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
                                  if path.exists(cmp_file):
                                  die('Comparison file already exists... abortingnRemove or rename '+cmp_file)

                                  # actual Word automation
                                  app = client.gencache.EnsureDispatch("Word.Application")
                                  app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
                                  app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
                                  app.ActiveDocument.SaveAs(cmp_file)

                                  print('Saved comparison as: '+cmp_file)
                                  app.Quit()

                                  def main():
                                  if len(argv) != 3:
                                  die('Usage: wrd_cmp <original_file> <modified_file>')
                                  cmp(argv[1], argv[2])

                                  if __name__ == '__main__':
                                  main()





                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    I created a more versatile version of this with path and file checks, if someone wants it...



                                    #!/usr/bin/python3
                                    # This uses win32com to automate the comparison of two Microsoft Word files.
                                    # Make sure to have win32com installed for your environment and python version:
                                    # https://github.com/mhammond/pywin32/releases
                                    # Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python

                                    from os import getcwd, path
                                    from sys import argv, exit
                                    from win32com import client

                                    def die(message):
                                    print (message)
                                    exit(1)

                                    def cmp(original_file, modified_file):
                                    dir = getcwd() + '\'
                                    print('Working...')

                                    # some file checks
                                    if not path.exists(dir+original_file):
                                    die('Original file does not exist')
                                    if not path.exists(dir+modified_file):
                                    die('Modified file does not exist')
                                    cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
                                    if path.exists(cmp_file):
                                    die('Comparison file already exists... abortingnRemove or rename '+cmp_file)

                                    # actual Word automation
                                    app = client.gencache.EnsureDispatch("Word.Application")
                                    app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
                                    app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
                                    app.ActiveDocument.SaveAs(cmp_file)

                                    print('Saved comparison as: '+cmp_file)
                                    app.Quit()

                                    def main():
                                    if len(argv) != 3:
                                    die('Usage: wrd_cmp <original_file> <modified_file>')
                                    cmp(argv[1], argv[2])

                                    if __name__ == '__main__':
                                    main()





                                    share|improve this answer













                                    I created a more versatile version of this with path and file checks, if someone wants it...



                                    #!/usr/bin/python3
                                    # This uses win32com to automate the comparison of two Microsoft Word files.
                                    # Make sure to have win32com installed for your environment and python version:
                                    # https://github.com/mhammond/pywin32/releases
                                    # Modified by 'pai' on basis of https://stackoverflow.com/questions/47212459/automating-comparison-of-word-documents-using-python

                                    from os import getcwd, path
                                    from sys import argv, exit
                                    from win32com import client

                                    def die(message):
                                    print (message)
                                    exit(1)

                                    def cmp(original_file, modified_file):
                                    dir = getcwd() + '\'
                                    print('Working...')

                                    # some file checks
                                    if not path.exists(dir+original_file):
                                    die('Original file does not exist')
                                    if not path.exists(dir+modified_file):
                                    die('Modified file does not exist')
                                    cmp_file = dir + original_file[:-5]+'_cmp_'+modified_file # use input filenames, but strip extension
                                    if path.exists(cmp_file):
                                    die('Comparison file already exists... abortingnRemove or rename '+cmp_file)

                                    # actual Word automation
                                    app = client.gencache.EnsureDispatch("Word.Application")
                                    app.CompareDocuments(app.Documents.Open(dir + original_file), app.Documents.Open(dir + modified_file))
                                    app.ActiveDocument.ActiveWindow.View.Type = 3 # prevent that word opens itself
                                    app.ActiveDocument.SaveAs(cmp_file)

                                    print('Saved comparison as: '+cmp_file)
                                    app.Quit()

                                    def main():
                                    if len(argv) != 3:
                                    die('Usage: wrd_cmp <original_file> <modified_file>')
                                    cmp(argv[1], argv[2])

                                    if __name__ == '__main__':
                                    main()






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Dec 10 '18 at 13:52









                                    paipai

                                    67154




                                    67154






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f47212459%2fautomating-comparison-of-word-documents-using-python%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Costa Masnaga

                                        Fotorealismo

                                        Sidney Franklin