python3读取docx、doc、docm文件

准备工作

语言python3

所需安装包:https://download.csdn.net/download/Da___Vinci/12037528

pip install 路径+包名即可安装

docx读取

from docx import Document

doc = Document(file_path)
#每一段的内容
for para in doc.paragraphs:
    print(para.text.encode('GBK','ignore').decode('GBK'))

doc、docm读取,需先转换为docx

from docx import Document
from win32com import client as wc

file_path = ''
word = wc.Dispatch("Word.Application")
doc = word.Documents.Open(file_path)
doc.SaveAs('测试.docx', 12)  #12代表docx
doc.Close()
word.Quit()

doc = Document('测试.docx')
#每一段的内容
for para in doc.paragraphs:
    print(para.text.encode('GBK','ignore').decode('GBK'))

整合版

from docx import Document
from win32com import client as wc
import os
import sys

def Read_DOC_File(file_path):
    result = ''
    if not os.path.isdir('Buffer'):  # 无文件时创建  Buffer文件夹,在工作目录下创建
        os.makedirs('Buffer')
    if file_path[-5:] == '.docx':
        doc = Document(file_path)
        for para in doc.paragraphs:  # 每一段的内容
            result = result+para.text.encode('GBK', 'ignore').decode('GBK')
    elif file_path[-4:] == '.doc' or file_path[-5:] == '.docm':
        word = wc.Dispatch("Word.Application")
        doc = word.Documents.Open(file_path)
        doc.SaveAs(sys.path[0]+r'\Buffer\1.docx', 12)
        doc.Close()
        word.Quit()
        doc = Document(sys.path[0]+r'\Buffer\1.docx')
        for para in doc.paragraphs: # 每一段的内容
            result = result + para.text.encode('GBK', 'ignore').decode('GBK')
    return result

file_path = r'****\****.docm'
print(Read_DOC_File(file_path))

python3读取docx、doc、docm文件_第1张图片

 

你可能感兴趣的:(python文件操作)