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

   2025-02-05 2930
核心提示:要使用Python3批量转换DOCX文档为TXT,可以使用python-docx库来实现。下面是一个简单的示例代码:from docx import Documentdef

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

from docx import Documentdef 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文件放置在与代码文件相同的目录中。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言