因文件格式要求,需要將docx 與doc文件相互轉(zhuǎn)換,特尋找python代碼,與大家共分享
from win32com import client #轉(zhuǎn)換doc為docx def doc2docx(fn): word = client.Dispatch("Word.Application") # 打開word應(yīng)用程序 #for file in files: doc = word.Documents.Open(fn) #打開word文件 doc.SaveAs("{}x".format(fn), 12)#另存為后綴為".docx"的文件,其中參數(shù)12或16指docx文件 doc.Close() #關(guān)閉原來word文件 word.Quit() #轉(zhuǎn)換docx為doc def docx2doc(fn): word = client.Dispatch("Word.Application") # 打開word應(yīng)用程序 #for file in files: doc = word.Documents.Open(fn) #打開word文件 doc.SaveAs("{}".format(fn[:-1]), 0)#另存為后綴為".docx"的文件,其中參數(shù)0指doc doc.Close() #關(guān)閉原來word文件 word.Quit() docx2doc(u"d:\\python\\1.docx")
如果想轉(zhuǎn)換為其他格式文件,需要在format文件名內(nèi)修改,并用如下save as 參數(shù)
doc.SaveAs("{}.pdf".format(fn[:-5]), 17)
需要說明的是:
要安裝OFFICE,如果是使用金山WPS的,則還不能應(yīng)用
補充:python批量將文件夾內(nèi)所有doc轉(zhuǎn)成docx
import os from win32com import client def doc_to_docx(path): if os.path.splitext(path)[1] == ".doc": word = client.Dispatch('Word.Application') doc = word.Documents.Open(path) # 目標路徑下的文件 doc.SaveAs(os.path.splitext(path)[0]+".docx", 16) # 轉(zhuǎn)化后路徑下的文件 doc.Close() word.Quit() path = ""#填寫文件夾路徑 doc_to_docx(path)
import os def find_file(path, ext, file_list=[]): dir = os.listdir(path) for i in dir: i = os.path.join(path, i) if os.path.isdir(i): find_file(i, ext, file_list) else: if ext == os.path.splitext(i)[1]: file_list.append(i) return file_list dir_path = "" ext = ".doc" file_list = find_file(dir_path, ext)
import os from win32com import client def doc_to_docx(path): if os.path.splitext(path)[1] == ".doc": word = client.Dispatch('Word.Application') doc = word.Documents.Open(path) # 目標路徑下的文件 doc.SaveAs(os.path.splitext(path)[0]+".docx", 16) # 轉(zhuǎn)化后路徑下的文件 doc.Close() word.Quit() def find_file(path, ext, file_list=[]): dir = os.listdir(path) for i in dir: i = os.path.join(path, i) if os.path.isdir(i): find_file(i, ext, file_list) else: if ext == os.path.splitext(i)[1]: file_list.append(i) return file_list dir_path = "C:\Users\python"#批量轉(zhuǎn)換文件夾 ext = ".doc" file_list = find_file(dir_path, ext) for file in file_list: doc_to_docx(file)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
標簽:昆明 錫林郭勒盟 文山 西寧 石家莊 梅州 懷化 浙江
巨人網(wǎng)絡(luò)通訊聲明:本文標題《python 實現(xiàn)docx與doc文件的互相轉(zhuǎn)換》,本文關(guān)鍵詞 python,實現(xiàn),docx,與,doc,文件,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。