pythondocx读取doc文件

一、python-docx读取docx文件

1. 安装python-docx包

pip install python-docx

2. python-docx读取docx文件

使用python-docx需要导入docx包

import docx

2. 读取docx文件段落和表格内容

import docx
import os.path
docxFile = 'text.docx'
doc = docx.Document(docxFile)
for para in doc.paragraphs:
  print(para.text)
for table in doc.tables:
  for row in table.rows:
    for cell in row.cells:
      print(cell.text)

二、使用office word将doc转换为docx

1. 安装pypiwin32

在windows操作系统上利用office word将doc文件转换为docx文件需要用到win32com包
使用win32com包需要安装pypiwin32包
pip install pypiwin32

2. doc转docx

import os.path
from win32com.client import Dispatch, DispatchEx
import docx

docPath = 'text.doc'
# wordApp = DispatchEx('Word.Application')
wordApp = Dispatch('Word.Application')
# 设置word不显示
wordApp.Visible = 0 
wordApp.DisplayAlerts = 0
docxPath = os.path.splitext(docPath)[0] + '.docx'
doc = wordApp.Documents.Open(docPath)
doc.SaveAs(docxPath, 12, False, '', True, '', False, False, False, False)
doc.Close()
wordApp.Quit()

3. python-docx读取docx问题

python-docx读取由office word转换doc得到的docx文件时,会导致部分内容得不到
例如由office word转换doc得到的docx文件中包含如下一段文字

使用python-docx读取的到的信息为日期:2012年,其中缺少了半段文字
暂未不知其原因

三、libreoffice将doc转docx

1. libreoffice

使用libreoffice将doc文件转换为docx文件使用如下代码
libreoffice --handless --convert-to docx [file] [--outdir] [dirPath]
其中docx指定转换后的文件类型
file表示doc文件的路径(包含文件名)
参数--outdir指定输出docx文件的路径(选填)
dirPath表示输出文件路径
例如
libreoffice --handless --convert-to docx text.doc --outdir ./
libreoffice --handless --convert-to docx text.doc

2. 问题

使用libreoffice将doc转换为docx可以避免第二部分第三节中描述的问题

原文地址:https://www.cnblogs.com/HanYG/p/15600225.html