Search code examples
pythonpsycopg2restructuredtext

How to break large cell into multiple lines and adjust table?


I'm using pytablewriter to write data from postgres to a rst grid table. My code is:

from pytablewriter import RstGridTableWriter as RST
import psycopg2

if __name__ == '__main__':
    with connection.cursor(name='foo') as cursor:
        cursor.itersize = 100000
        cursor.execute(query)

        for raw_row in cursor:
            row = [
                raw_row[0],
                raw_row[1],
                raw_row[2],
                ', '.join([item for item in raw_row[3] if item])
            ]

            matrix.append(row)

    writer = RST(
        table_name='DocTable',
        headers=['col1', 'col2', 'col3', 'col4'],
        value_matrix=matrix
    )

    writer.dump('./sample.rst')

The last value of each row fetched is a list of strings. For every iteration, the code above turns the list of strings into a comma separated string. That string can be potentially large and result in a large column.

I'd like to know how to output a table with fixed width for each column and break large columns into multiple lines. Example:

Cell: "Lorem,ipsum,dolor,sit,amet,consectetur,adipiscing,elit,sed,do,eiusmod,tempor,incididunt,ut,labore,et,dolore,magna,aliqua.,Ut,enim,ad,minim,veniam,quis,nostrud,exercitation,ullamco,laboris,nisi,ut,aliquip,ex,ea,commodo,consequat"

Turns into:

'Lorem,'
'ipsum,'
'dolor,'
'sit,'
'amet,'
'consectetur,'
'adipiscing,'
'elit,'
'sed,'
'do,'
'eiusmod,'
'tempor,'
'incididunt,'
'ut,'
'labore,'
'et,'
'dolore,'
'magna,'
'aliqua.,'
'Ut,'
'enim,'
'ad,'
'minim,'
'veniam,'
'quis,'
'nostrud,'
'exercitation,'
'ullamco,'
'laboris,'
'nisi,'
'ut,'
'aliquip,'
'ex,'
'ea,'
'commodo,'
'consequat'

And all other cells are properly adjusted as well.

I've tried to write it as ',\n'.join([item for item in raw_row[3] if item]) but does not work.


Solution

  • You could do this without altering your data through custom CSS with the nth-child selector and the rst-class directive.

    Very roughly, and assuming the fourth column is the trouble.

    file.rst

    .. rst-class:: my-table
    
    [pytablewriter output]
    

    custom.css

    table.my-table tbody tr td:nth-child(4) {
        width: 30%;
    }