怎么使用python3批量转换DOCX文档为TXT

2024-01-18

要使用Python3批量转换DOCX文档为TXT,可以使用python-docx库来实现。下面是一个简单的示例代码:

from docx import Document

def convert_docx_to_txt(docx_file, txt_file):
    doc = Document(docx_file)
    with open(txt_file, 'w', encoding='utf-8') as f:
        for paragraph in doc.paragraphs:
            f.write(paragraph.text + '\n')

# 批量转换
docx_files = ['file1.docx', 'file2.docx', 'file3.docx']
for docx_file in docx_files:
    # 构建输出文件名
    txt_file = docx_file.replace('.docx', '.txt')
    convert_docx_to_txt(docx_file, txt_file)

上述代码中,convert_docx_to_txt函数接受一个DOCX文件路径和一个TXT文件路径作为输入,将DOCX文档的内容逐行写入TXT文件中。然后,使用docx_files列表存储需要转换的DOCX文件名,循环遍历列表中的每个文件,调用convert_docx_to_txt函数进行转换。

请注意,代码中使用的是python-docx库,因此您需要先安装该库。您可以使用以下命令来进行安装:

pip install python-docx

请确保您已经安装了Python 3和pip,并且将DOCX文件放置在与代码文件相同的目录中。