Benjamin Jones
Benjamin Jones

Reputation: 997

Unable to tabulate data read in from file

My code in fruitveggielist.py should read the file and print to table. I am using tabulate

fruit.txt

corn, apple
lettuce, grapes
pepper, melon

However should be shown in table with headers veggie fruit.

Code so far:

from tabulate import tabulate
filepath = 'fruit.txt'
with open(filepath) as fp:
   line = fp.readline()

   while line:
           print tabulate("{}".format(line.strip()), headers=['Veggie', 'Fruit'])
           line = fp.readline()

Print-

Veggie
--------
c
o
r
n
,

a
p
p
l
e

etc,etc...

How would I use tabulate or another table formater to correctly print fruit.txt to a table?

Upvotes: 1

Views: 225

Answers (1)

cs95
cs95

Reputation: 402553

Okay, so the easiest way to do this is to put your data inside a nested list.

As you're doing it now, strings are treated as iterables, so each character is treated as a separate item and given its own row. You also end up putting headers over each row of data read in.

As mentioned before, the best way to solve this would be to put everything into a list and call the function once. Each pair should be a separate record.

from tabulate import tabulate

data = []
with open('fruit.txt') as f:
     for line in f:
        data.append(list(map(str.strip, line.split(','))))

print(tabulate(data, tablefmt='grid', headers=('veggie', 'fruit')))

+----------+---------+
| veggie   | fruit   |
+==========+=========+
| corn     | apple   |
+----------+---------+
| lettuce  | grapes  |
+----------+---------+
| pepper   | melon   |
+----------+---------+

Upvotes: 1

Related Questions