python 把一个文件夹下的docx转化为doc

来源:互联网 发布:python amf 编辑:程序博客网 时间:2024/05/16 08:38

因为要用java批量处理word文档的需要,需要用到的类型是doc,可是待处理的文档却是docx格式的,所以有了批量将docx转化为doc的需要,下面的脚本用于遍历一个文件夹下将所有的docx文档另存为doc,普通的重命名虽然最终得到的doc可以用docx打开操作,但其实内部的格式与doc是不吻合的,当用java的第三方工具读取时会出错,下面的函数应用到了python win32 的功能,SaveAs(docxFullName,1)中,后面的参数设为1,那么保存得到的文件将是doc格式的


#coding=gb2312


from win32com import client as wc
import os
word = wc.Dispatch('Word.Application')

#word.Visible = True #是否可见  
#word.DisplayAlerts = 0  
def docx2doc(dir):
    i=0
    j=0
    for path, subdirs, files in os.walk(dir):
        for wordFile in files:
            


            wordFullName = os.path.join(path, wordFile)
            
            dotIndex = wordFile.rfind(".")
            
            if(dotIndex!=-1):
                try:    
                    fileSuffix = wordFile[(dotIndex + 1) : ]
                    if(fileSuffix == "docx"):
                        fileName = wordFile[:dotIndex]
                        docxName = fileName + ".doc"
                
                        docxFullName = os.path.join(r'E:\docx2docResult', docxName)
                        print '正在转化:'+wordFullName
                        doc = word.Documents.Open(wordFullName)
                        i+=1
                        doc.SaveAs(docxFullName,1)
                        doc.Close()
                except Exception:
                    j+=1
                    print wordFullName+':该文件保存失败****************************************'

                


    word.Quit()
    print '尝试转换'+str(i)+'个docx'
    print '其中成功的有:'+str(i-j)+'个'
    print '失败的共有:'+str(j)+'个'
    
if __name__ == '__main__':
    
    docx2doc(r"E:\folder")
    
    
    
    
原创粉丝点击