python转换doc文档为docx格式后,提取文档段落内容后保存
from docx import Document
import os
import docx
import win32com.client as wc
filePath = "C:/Users/现有数据字典/"
word = wc.Dispatch("Word.Application")
os.chdir(filePath)
for root, dirs, files in os.walk(r'%s' % (filePath), topdown=False):
for file_name in files:
if '.doc' in file_name:
doc = word.Documents.Open(root+file_name)
op = file_name.split('.')[0]
newfile_name = op+'.docx'
doc.SaveAs(root+newfile_name, 12, False, "", True, "", False, False, False, False)
doc.Close
word.Quit
document = Document(root+newfile_name)
all_paragraphs = document.paragraphs
for paragraph in all_paragraphs:
with open(filePath+"test.txt","a+") as f:
f.writelines('\n'+paragraph.text)
这里是文件夹中已有docx文件,则不需要转换步骤:
from docx import Document
import os
import docx
import win32com.client as wc
filePath = "C:/Users/现有数据字典/"
word = wc.Dispatch("Word.Application")
os.chdir(filePath)
for root, dirs, files in os.walk(r'%s' % (filePath), topdown=False):
for file_name in files:
if '.docx' in file_name:
document = Document(root+file_name)
all_paragraphs = document.paragraphs
for paragraph in all_paragraphs:
with open(filePath+"test.txt","a+") as f:
f.writelines('\n'+paragraph.text)