Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python-docx how do I delete a table row?

I can't figure out how to delete a table row in python-docx. Specifically, my tables come in with a header row and a row that has a special token stored in the text of the first cell. I search for tables with the token and then fill in a bunch of rows of the table. But how do I delete row 1, which has the token, before adding new rows? I tried

table.rows[1].Delete() and table.rows = table.rows[0:1]

The first one fails with an unrecognized function (the documentation refers to this function in the Microsoft API, but I don't know what that means). The second one fails because table.rows is read-only, as the documentation says.

So how do I do it?

like image 342
All The Rage Avatar asked Apr 06 '19 03:04

All The Rage


1 Answers

This functionality is not built-in, which really shocks me. As I search forums I find many people asking for this over the last five years. However, a workaround exists and here it is:

def remove_row(table, row):
    tbl = table._tbl
    tr = row._tr
    tbl.remove(tr)
    
row = table.rows[n]
remove_row(table, row)
like image 166
All The Rage Avatar answered Sep 26 '22 22:09

All The Rage