Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Python Docx to remove blank lines

I am using Python docx to remove blank lines from documents containing text and images. Using the paragraph.clear() and paragraph.run.clear() works to a point, but the outputted file still has blank lines which only have a paragraph mark shown in Word. Is there a way of searching directly for paragraph marks? Or is there a better way of clearing the lines?

# code snippet
for paragraphs in document.paragraphs:
    if paragraphs.text == "\n":
        paragraphs.clear()
like image 541
Tom Avatar asked Sep 12 '26 22:09

Tom


2 Answers

This removed all the empty lines for me in my document file

for paragraph in doc.paragraphs:
   if len(paragraph.text) == 0:
      p = paragraph._element
      p.getparent().remove(p)
      p._p = p._element = None
like image 170
Adam Marciszewski Avatar answered Sep 14 '26 12:09

Adam Marciszewski


Empty lines are not marked by "\n" but by empty string "".

Plus, clear() removes text but not the paragraph itself.

Try to test len(paragraph.text)==0 for each paragraph.

like image 31
Setop Avatar answered Sep 14 '26 13:09

Setop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!