Python Script-merge Word__python

Source: Internet
Author: User
Tags glob python script
#-*-coding:utf-8-*-
Import OS
Import Sys
Import Fnmatch
Import Glob
From win32com import client as WC

#将文件夹下的word文件转化为txt文件
Def word2txt ():
Path= ' D:\code\my_projects\project01\source '
Word=wc.gencache.ensuredispatch (' Word.Application ')
Try
For path,dirs,files in Os.walk (path):
For filename in Files:
If not fnmatch.fnmatch (filename, ' *.doc '): Continue
Doc=os.path.abspath (Os.path.join (path,filename))
print ' processing%s ... '% doc
Word. Documents.Open (DOC)
docastext=doc[:-3]+ ' txt '
Word. Activedocument.saveas (Docastext,fileformat=wc.constants.wdformattext)
Word. Activedocument.close ()
Finally
Word. Quit ()

#将转化得到的txt文件合并成一个txt
Def txt_merge ():
Finlist=glob.glob (' D:\code\my_projects\project01\source\*.txt ')
F=open (' D:\code\my_projects\project01\source\p01.txt ', ' W ')
For the fin in finlist:
X=open (FIN, ' r ')
F.write (X.read ())
X.close ()
F.close ()

#将合并的txt文件修改为word文件 (here directly modify the suffix name), delete the resulting TXT file
Def Txt2word ():
Portion=os.path.splitext (' D:\code\my_projects\project01\source\p01.txt ')
newname=portion[0]+ '. Doc '
Os.rename (' D:\code\my_projects\project01\source\p01.txt ', newname)
Txtlist=glob.glob (' D:\code\my_projects\project01\source\*.txt ')
For txtfile in Txtlist:
Os.remove (txtfile)
Print u ' merged file as P01.doc '

#主函数
def main ():
Word2txt ()
Txt_merge ()
Txt2word ()

if __name__ = = "__main__":
Main ()
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.