python调用compare工具_Python win32com模块:CompareDocuments - python代码 - 源码查

问题

I am trying to programmatically use Word's built-in Compare function to do a diff of two versions of the same Word document in git.

I've just been trying to get the compare portion of the code off the ground, by using the Python win32com module. Here's what I have so far:

import win32com.client as win32

word = win32.gencache.EnsureDispatch('Word.Application')

word.CompareDocuments('old.docx', 'new.docx')

But when I run this code, I get the following error:

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

I don't know much about the win32com module or COM objects in general, am I misusing this function? Is there a better module for calling Word's compare function? I don't want to just save the Word docs as text and diff the text, and I prefer to use Python.

Thank you.

解决方法

The arguments that must be passed into CompareDocuments() are not paths (strings) to the files, but instead of the Document class type. You must first open the Word documents and then pass those into CompareDocuments():

import win32com.client as win32

word = win32.gencache.EnsureDispatch('Word.Application')

doc_old = word.Documents.Open('C:/abs/path/to/file/old.docx')

doc_new = word.Documents.Open('C:/abs/path/to/file/new.docx')

word.CompareDocuments(doc_old, doc_new)

Notice that you must provide the absolute path to the file when opening, or else win32com cannot find it.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值