美文网首页
Python修改文档格式.docx转为.doc

Python修改文档格式.docx转为.doc

作者: cherishpf | 来源:发表于2020-06-23 15:12 被阅读0次

Python处理docx文件需要先安装python_docx模块

pip install python_docx  
注意:不是 pip install docx
"""
修改文档格式.docx转为.doc,并保存到当前目录的doc目录下,需要提前创建doc目录
"""
import pythoncom
import os
from docx import Document


# 从最后开始替换某字符串几次
def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)


# 读取文件夹下的docx文件名列表
def docx_file_name(file_dir):
    fileList = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if os.path.splitext(file)[1] == '.docx':
                fileList.append(os.path.join(root, file))
    return fileList


# docx文件另存为doc
def docx_to_doc(docxName):
    pythoncom.CoInitialize()
    try:
        doc = Document(docxName)
        docxName = rreplace(docxName, "\\", "\\doc\\", 1)
        doc.save(docxName.replace(".docx", ".doc"))
    except Exception as e:
        print(e.message)
    finally:
        # 释放资源
        pythoncom.CoUninitialize()


def main():
    fileList = docx_file_name("D:\\文件处理\\2020.6.24文章-docx")
    print(len(fileList))
    for file in fileList:
        docx_to_doc(file)


if __name__ == '__main__':
    main()

相关文章

网友评论

      本文标题:Python修改文档格式.docx转为.doc

      本文链接:https://www.haomeiwen.com/subject/cnrhfktx.html