Search code examples
pythonoutputtabular

How to format a text file into even tabular format?


I'm trying to display a bunch of lines from a text file as a table. The text file looks something like this:

capital|What is the capital of Egypt?|Cairo|3
pi|What is pi to two digits?|3.14|3
dozen|How many eggs in a dozen?|12|1
president|Who was the first president?|Washington|1

I'd like to have my code spit out a formatted output that would look something like this:

capital      What is the capital of Egypt?   Cairo        3
pi           What is pi to two digits?       3.14         3
dozen        How many eggs in a dozen?       12           1
president    Who was the first president?    Washington   1

Here's the code I've come up with, but the output is nowhere near looking like the way I want it to.

f = open('quest_load.txt', 'r')
contents = f.read()
contents1 = contents.replace('|','     ')
print(contents1)
f.close()

Solution

  • Loop through the data once, to discover the maximum width of each column:

    with open('quest_load.txt', 'r') as f:
        for i, line in enumerate(f):
            if i == 0:
                max_widths = [len(col) for col in line.split('|')]
                continue
            max_widths = [
                max(len(col), curr_max)
                for col, curr_max in zip(line.split('|'), max_widths)
            ]
    

    Then loop again to print the columns, formatting each column according to max width:

    with open('quest_load.txt', 'r') as f:
        for line in f:
            content = line.split('|')
            formatted = [
                f'{substr: <{width}}'
                for substr, width in zip(content, max_widths)
            ]
            print('\t'.join(formatted), end='')
    

    Output:

    capital     What is the capital of Egypt?   Cairo       3
    pi          What is pi to two digits?       3.14        3
    dozen       How many eggs in a dozen?       12          1
    president   Who was the first president?    Washington  1