將.doc轉換為.docx文件有幾種常用的方法:
- Microsoft Word 和 WPS 自帶.doc轉換.docx功能,但只能一個文件一個文件轉換,批量轉換要會員
- 在線網頁 Office-Converter.com 等在線網頁轉換工具,以前很好用,現在也開始收費了
作為白嫖黨,不想花錢沖會員又不想一個個打開一個個轉換,故寫此腳本。
1 import os 2 import time 3 from win32com import client as wc 4
5 path1 = 'E:/waiting/' # 需要修改的文件的路徑
6 path2 = 'E:/saving/' # 存儲的路徑
7
8 for file in os.listdir(path1): 9
10 if file.endswith('.doc'): 11 word = wc.Dispatch("Word.Application") 12 out_name = file.replace("doc", r'docx') # doc文件修改后綴名
13 in_file = os.path.abspath( path1 + "\\" + file) 14 out_file = os.path.abspath( path2 + "\\" + out_name) 15 print(in_file) 16 print(out_file) 17
18 doc = word.Documents.Open(in_file) 19 doc.SaveAs(out_file, 12, False, "", True, "", False, False, False, False) 20 doc.Close() 21
22 print('轉換成功') 23 word.Quit() 24 time.sleep(3) # 避免文件未關閉就打開下一個文件
25
26 else: 27 word = wc.Dispatch("Word.Application") 28 out_name = file # 不是doc文件則不修改后綴名
29 in_file = os.path.abspath( path1 + "\\" + file) 30 out_file = os.path.abspath( path2 + "\\" + out_name) 31 doc = word.Documents.Open(in_file) 32 print(in_file) 33 print(out_file) 34
35 doc.SaveAs(out_file, 12, False, "", True, "", False, False, False, False) 36 doc.Close() 37
38 print('復制成功') 39 word.Quit() 40 time.sleep(3) # 避免文件未關閉就打開下一個文件
41
直接復制代碼,修改 path1 和 path2 路徑即可使用,取走請留言。