使用python-docx提取文档尺寸

有朋友处理教育类的手抄报,文档较多,每个文件打开去看尺寸十分麻烦,为了方便进行分类,制作了一个根据文档尺寸分类并放到相应目录的功能,使用的PyQt5 + Python制作,下面贴出核心代码给大家分享,本文为个人原创,如需转载请标明出处。

    # 循环读取指定目录下的所有文件
    for root,dirs,files in os.walk(UI.filePath.text()):
        for file in files:
            try:
                # 如果文件名最后4个字符不是docx则跳过
                # 由于是使用的python-docx插件,所以只能处理docx格式的文档
                if file[-4:] != "docx":
                    continue
                # 使用python-docx的Document方法打开一个文档
                doc = Document("/".join([root,file]))
                # 直接从sections._document_elm.sectPr_lst[0].page_width读取文档的宽度信息
                # 其中/36000 是一个经验,是先根据A4文档的210*297倒推出来的比例
                width = int(doc.sections._document_elm.sectPr_lst[0].page_width / 36000)
                height = int(doc.sections._document_elm.sectPr_lst[0].page_height / 36000)
                # 将width和height值作为新文件夹的名称
                outPath = UI.outPath.text() + str(width) + "x" + str(height)
                # 如果新的目录不存在则新建
                if not os.path.exists(outPath):
                    os.makedirs(outPath)
                if outPath[-1] != "/":
                    outPath += "/"
                # 将文档移到新建的目录中
                shutil.move("/".join([root,file]),outPath + file)
                print("文件:{} 宽:{} 高:{}".format("/".join([root,file]), width, height))
            except:
                continue
    # 由于使用的是PyQt5制作的界面,所以使用QMessageBox进行提示
    QMessageBox.about(main, "完成", "分类已完成!")

猜你喜欢

转载自blog.csdn.net/wudechun/article/details/101796156