一、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可以避免第二部分第三節中描述的問題