astanin / python-tabulate

Pretty-print tabular data in Python, a library and a command-line utility. Repository migrated from bitbucket.org/astanin/python-tabulate.
https://pypi.org/project/tabulate/
MIT License
2.1k stars 163 forks source link

How to "\n" empty line before table #264

Closed smoochy closed 1 year ago

smoochy commented 1 year ago

I am not using the normal print() method to output the result I get from an DB query into a tabulate table. I use an own logging handler. Because of this, the header of the table is part of the first log message and then gets a line feed. It looks like this:

image

To get the table, I call it like this:

logger.info(
    tabulate(
        sql_result,
        headers=["Location", "Date", "Temperature"],
        tablefmt="pretty",
        numalign="decimal",
        ),
    )

I played around with f-formatted strings, but this only messes up the output from tabulate. Also putting the result from the DB (sql_result) into brackets does not work. The result I am getting from the DB looks like this:

[('Dresden', '2023-03-17', 6.8), ('Dresden', '2023-03-18', 9.5), ('Dresden', '2023-03-19', 10.0), ('Dresden', '2023-03-20', 9.5)]

Does anyone know, how I could accomplish this?

Cheers.

nacezavrtanik commented 1 year ago

The output of the tabulate function is actually just a string, so prepending a '\n' should work, like this:

>>> data = [[1, 2, 3], ['a', 'b', 'c']]
>>> LOGGER.info('\n' + tabulate(data))
2023-04-27 20:32:17 INFO [<input>:<module>:1]:  
-  -  -
1  2  3
a  b  c
-  -  -

Hope this helps. 😄

smoochy commented 1 year ago

Thank you very much and actually this worked.

I don't know, why I did not think of simply combining it. Like said, I tried with f"{\n}" and it did not work. Sometimes the easiest solution is the correct one :)

logger.info(
    "\n"
    + tabulate(
        dbc.cursor.fetchall(),
        headers=["Location", "Date", "Temperature"],
        tablefmt="pretty",
        numalign="decimal",
        ),
    )