# How to Create Footer for Python PrettyTable

I'm looking to add a footer to my PrettyTable, totalling the data stored in the rows above. I've created a count in the script, but I'd like to add this into the table.

The code I have to create the table below is as follows (`.add_row` is in a loop):

``````outTbl = PrettyTable(["Projects", "Number"])
``````

...which generates a table looking like this:

``````+--------------------------+-----------+
|        Projects          |   Number  |
+--------------------------+-----------+
|        Project A         |     5     |
|        Project B         |     9     |
|        Project C         |     8     |
|        Project D         |     2     |
+--------------------------+-----------+
``````

...but I'm looking for the functionality to create the above table with a summary footer at the bottom:

``````+--------------------------+-----------+
|        Projects          |   Number  |
+--------------------------+-----------+
|        Project A         |     5     |
|        Project B         |     9     |
|        Project C         |     8     |
|        Project D         |     2     |
+--------------------------+-----------+
|          Total           |     24    |
+--------------------------+-----------+
``````

I've searched the module docs online: PrettyTable tutorial, Google prettytable - Tutorial and can't see any reference to a footer, which I find surprising given header is one. Can this be done in PrettyTable, or is there another Python module with this functionality anyone can recommend?

You can use texttable with small hack around it:

``````import texttable

table = texttable.Texttable()
['Project A\nProject B\nProject C\nProject D', '5\n9\n8\n2'],
['Total', 24]])
print(table.draw())
``````

Output:

``````+-----------+--------+
| Projects  | Number |
+===========+========+
| Project A | 5      |
| Project B | 9      |
| Project C | 8      |
| Project D | 2      |
+-----------+--------+
| Total     | 24     |
+-----------+--------+
``````

There is no separate function to create footer in pretty table. However you can do little trick to create, in case you are particular to use only pretty table as follows

``````sum = 0
for row in outTbl:
sum = sum + int(row.get_string(fields=["Number"]).split('\n').replace('|','').replace(' ',''))
print (outTbl)
`````` or if you are looking for particular function with footers you can look at https://stackoverflow.com/a/26937531/3249782 for different approaches you can use

I had the same problem today and used the following approach to treat the last n lines of my table as result lines that are seperated by a horizontal line (like one that is separating the header):

``````from prettytable import PrettyTable

t = PrettyTable(['Project', 'Numbers'])

# NOTE: t is the prettytable table object
# Get string to be printed and create list of elements separated by \n
list_of_table_lines = t.get_string().split('\n')

# Use the first line (+---+-- ...) as horizontal rule to insert later
horizontal_line = list_of_table_lines

# Print the table
# Treat the last n lines as "result lines" that are seperated from the
# rest of the table by the horizontal line
result_lines = 1
print("\n".join(list_of_table_lines[:-(result_lines + 1)]))
print(horizontal_line)
print("\n".join(list_of_table_lines[-(result_lines + 1):]))
``````

This results in the following output:

```+-----------+---------+
|  Project  | Numbers |
+-----------+---------+
| Project A |    5    |
| Project B |    9    |
| Project C |    8    |
+-----------+---------+
| Project D |    2    |
+-----------+---------+
```

I know I'm late but I've created a function to automagically append a "Total" row to the table. For now NOT resolving if the column is wider than the table.

Python3.6++

Function:

``````def table_footer(tbl, text, dc):
res = f"{tbl._vertical_char} {text}{' ' * (tbl._widths - len(text))} {tbl._vertical_char}"

for idx, item in enumerate(tbl.field_names):
if idx == 0:
continue
if not item in dc.keys():
res += f"{' ' * (tbl._widths[idx] + 1)} {tbl._vertical_char}"
else:
res += f"{' ' * (tbl._widths[idx] - len(str(dc[item])))} {dc[item]} {tbl._vertical_char}"

res += f"\n{tbl._hrule}"
return res
``````

Usage:

``````tbl = PrettyTable()
tbl.field_names = ["Symbol", "Product", "Size", "Price", "Subtotal", "Allocation"]

print(tbl)
print(table_footer(tbl, "Total", {'Subtotal': 50000, 'Allocation': '29 %'}

+--------+-------------------------------+-------+---------+----------+------------+
| Symbol |            Product            |  Size |  Price  | Subtotal | Allocation |
+--------+-------------------------------+-------+---------+----------+------------+
|    AMD |   Advanced Micro Devices Inc  | 999.9 |  75.99  |  20000.0 |      23.00 |
|   NVDA |          NVIDIA Corp          |  88.8 |  570.63 |  30000.0 |       6.00 |
+--------+-------------------------------+-------+---------+----------+------------+
| Total  |                               |       |         |    50000 |       29 % |
+--------+-------------------------------+-------+---------+----------+------------+
``````

After inspecting the source code of pretty table you can see that after you print the table you can get each column width. Using this you can create a footer by yourself, because pretty table do not give you that option. Here is my approach:

``````from prettytable import PrettyTable

t = PrettyTable(['Project', 'Numbers'])
print(t)
total = '24'
tb_width = sum(t._widths)
print('| ' + 'Total' + (' ' * (tb_width - len('Total' + total)) +
' ' * padding_bw) + total + ' |')
print('+-' + '-' * tb_width + '-' * padding_bw + '-+')

``````

And here is the output:

``````+-----------+---------+
|  Project  | Numbers |
+-----------+---------+
| Project A |    5    |
| Project B |    9    |
| Project C |    8    |
| Project D |    2    |
+-----------+---------+
| Total            24 |
+---------------------+
``````

Just change the total var in the code and everything should be working fine

I stole @Niels solution and did this function to print with a delimiter before the last `num_footers` lines:

``````def print_with_footer(ptable, num_footers=1):
""" Print a prettytable with an extra delimiter before the last `num` rows """
lines = ptable.get_string().split("\n")
hrule = lines
lines.insert(-(num_footers + 1), hrule)
print("\n".join(lines))
``````

prettytable has supported footer by passing `divider=True` to `add_row()`.

Here is an example from https://pypi.org/project/prettytable/

code:

``````x = PrettyTable()
x.field_names = ["City name", "Area", "Population", "Annual Rainfall"]
``````

output:

``````+-----------+------+------------+-----------------+
| City name | Area | Population | Annual Rainfall |
+-----------+------+------------+-----------------+
|  Adelaide | 1295 |  1158259   |      600.5      |
|  Brisbane | 5905 |  1857594   |      1146.4     |
|   Darwin  | 112  |   120900   |      1714.7     |
|   Hobart  | 1357 |   205556   |      619.5      |
+-----------+------+------------+-----------------+
| Melbourne | 1566 |  3806092   |      646.9      |
|   Perth   | 5386 |  1554769   |      869.4      |
|   Sydney  | 2058 |  4336374   |      1214.8     |
+-----------+------+------------+-----------------+
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.7284574,"math_prob":0.7417457,"size":1258,"snap":"2023-40-2023-50","text_gpt3_token_len":284,"char_repetition_ratio":0.3165869,"word_repetition_ratio":0.28865978,"special_character_ratio":0.45071542,"punctuation_ratio":0.12707183,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9774734,"pos_list":[0,1,2],"im_url_duplicate_count":[null,2,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-12-05T20:07:11Z\",\"WARC-Record-ID\":\"<urn:uuid:98fa6d0d-1847-416d-9b84-77376d2f8df4>\",\"Content-Length\":\"229871\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:27dfedda-8c48-4b24-a148-24b9d451e81d>\",\"WARC-Concurrent-To\":\"<urn:uuid:9bfe64d4-eba9-4d85-bbde-734c72cc5b34>\",\"WARC-IP-Address\":\"172.64.155.249\",\"WARC-Target-URI\":\"https://stackoverflow.com/questions/56150310/how-to-create-footer-for-python-prettytable/67478676\",\"WARC-Payload-Digest\":\"sha1:JJYJLWLVVV3I5SNIGKJ6F2PTVWP6QTHV\",\"WARC-Block-Digest\":\"sha1:HTEDBYLRFEWSZNV32MUOSNC2F6VZJSMU\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-50/CC-MAIN-2023-50_segments_1700679100555.27_warc_CC-MAIN-20231205172745-20231205202745-00003.warc.gz\"}"}