Search code examples
pythonimporttabulate

My imported .txt table does not line up correctly with the headers (Python)


So basically I have to import a preset .txt file and everything works fine except for the one small thing that the preset headers that are in the code don't line up with the .txt file data properly.

import csv
from tabulate import tabulate as tb



F = input("Enter the name of the file that you would like to import:")
fields = list(csv.reader(open(F + '.txt', 'r'), delimiter=';'))
print(tb(fields, headers=['Company', 'Registration number.', 'Date', 'Adress', 'Telephone Number']))

And the code prints out this.

          Company  Registration number.    Date                                Adress  Telephone Number
------  ---------  ----------------------  -----------------------------  -----------  ------------------
Valve    60006672  03.13.2003.             Brown street, Athens, Greece.  14223157963
Google   50003495  10.24.2001.             Lenin street, Moscow, Russia.  53221745750
Apple    20000196  03.31.2008.             Second street, New York, USA.  55327537161


The information in .txt file:

Valve; 60006672;03.13.2003.;Brown street, Athens, Greece..;14223157963; Google;50003495;10.24.2001.;Lenin street, Moscow, Russia.;53221745750; Apple;20000196;03.31.2008.;Second street, New York, USA.;55327537161;


Solution

  • Question: Table output does not line up correctly with the headers?

    The last ; in every line leads to one more Column.

    Valve; 60006672;03.13.2003.;Brown street, Athens, Greece..;14223157963; 
    

    Therefore the count of your headers= is less by one.

    Solution:

    Either remove the last ';' from every line or append a empty '' to headers=

    tb(fields, 
       headers=['Company', 'Registration\nNumber', 'Date',
                'Adress', 'Telephone\nNumber', '']
      )
    

    Output:

    Company  Registration  Date         Adress                            Telephone
                   Number                                                    Number
    --------- -----------  -----------  ------------------------------  -----------  --
    Valve        60006672  03.13.2003.  Brown street, Athens, Greece..  14223157963
    Google       50003495  10.24.2001.  Lenin street, Moscow, Russia.   53221745750
    Apple        20000196  03.31.2008.  Second street, New York, USA.   55327537161