Search code examples
pythonpython-3.xpython-3.7ascii-artprettytable

Python - PrettyTable, if text in one column is long is it possible to set it in new row?


my trouble is this: I would like to set text I have in tab separated format to a nice ASCII table. I can do that using prettytable and this is not my problem currently. The problem is that I have one column that have long text, and I would like for prettytable to cut that text in smaller parts.

What I have now:

+------+------+--------------------------------------------------+
| Col1 | Col2 |                         Col3                     |
+----------------------------------------------------------------+
|     a|     b| 123456789123456789123456789123456789123456789123 |
|     d|     e| 123456789123456789123456789123456789123456789123 |
+------+------+--------------------------------------------------+

What I would like to have:

+------+------+---------------------+
| Col1 | Col2 |        Col3         |
+---------------------------- ------+
|     a|     b| 1234567891234567891 |
|      |      | 2345678912345678912 |
|      |      |      3456789123     |
|     d|     e| 1234567891234567891 |
|      |      | 2345678912345678912 |
|      |      |      3456789123     |
+------+------+---------------------+

My code is as follows:

import re
from prettytable import PrettyTable

imported = open("import_file.txt", "r")
x = PrettyTable()
x.field_names = ["Col1", "Col2", "Col3"]
for i in imported:
    red = re.split(r'\t', i)
    x.add_row(red)
with open('exit_file.txt', 'w') as exitfile:
    exitfile.write(str(x))

Is it possible to do something like that easy in python3 using prettytable or should I use some other module?


Solution

  • I am not sure if there's a function that allows you to do this in prettytable but there's a simple workaround to achieve exactly what you want. However, this requires you to amend your import_file.txt directly or parse and apply changes before adding the values to the table.

    Here's an example

    ['1', '2', '3'] 
    

    if converted in such a format

    print("\n".join(['1', '2', '3'])
    

    will print the characters line by line.

    And therefore adding a line break in your characters will force them to break the current line and start a new line within the same cell([row][col]=cell).