"""python-docx删除段落(含回车符)v202111211833
工作中需要把微信收藏文章复制到docx(仅保留文本),会出现空行及
不需要的单行,于是试写了如次代码。
"""
import pathlib
from docx import Document
docx = Document()
paths = pathlib.Path("d:\\sucai").rglob("*.docx")#限定扩展名以免运行出错
for path in paths:
doc = Document(path)
filename = doc.paragraphs[0].text
for p in doc.paragraphs:
# 以下3行代码删除小于50个字符的行(含空行)
if len(p.text) < 50 and p.text != filename:
CT_P = p._element
CT_P.getparent().remove(CT_P)
doc.save('d:\\sucai\\' + filename + '.docx')