一、基本介绍
1.doc文件和docx文件的区别:
doc是早一代的文件格式
docx是开放格式,本质上是一个zip文件
docx文件的格式:
二、python-docx模块使用误区:
python中的python-docx模块只支持解析.docx格式的文件,不支持.doc格式的文件。因为上述我们说到的doc文件与docx文件是有区别的。
下面是python-docx解析.docx格式文件,并保存为txt格式的演示代码:
from docx import Document
def convert_docx_to_txt(docx_file, txt_file):
try:
# 打开 .docx 文件
doc = Document(docx_file)
# 创建或打开 .txt 文件以写入模式
with open(txt_file, 'w', encoding='utf-8') as f:
# 将 .docx 文件中的每个段落写入 .txt 文件
for para in doc.paragraphs:
f.write(para.text + '\n')
print("转换成功!")
except Exception as e:
print("发生错误:", str(e))
# 指定输入的 .docx 文