1

I'm having the following function which picks results from a results.txt file and displays it to the user, the first row comes out nicely but the rest of the results are not well-aligned. I'm not sure what's causing this. here's the function

def show_result():
'''prints the score list'''
file_exist()
print_whole_list = []
print("Results")
print("*"*41)
result = open("results.txt","r")
res = result.readlines()
print("Name:      Lap1:      Lap2:      Lap3:    In total:     Average:")
for i in res:
    temp_list = i.split(";")
    total = int(temp_list[1]) + int(temp_list[2]) + int(temp_list[3])
    average = int(total) / 3.0
    average = round(average, 2)
    temp_list.insert(4, total)
    temp_list.insert(5, average)
    print_whole_list.extend(temp_list)
for row in print_whole_list:
    print("{0:{width}}".format(row, width=10), end=' ')
result.close()

The records in the text file:

Kembos;23;43;23;
Moses;42;51;43;
Ben;43;23;21;

output

Nelewout
  • 6,281
  • 3
  • 29
  • 39
Jay
  • 11
  • 4

1 Answers1

0

You can use tabulate instead to populate your data in a tabular format in python

from tabulate import tabulate

result = open("results.txt","r")
res = result.readlines()
final = []
for line in res:
    temp_list = line.split(';')[:-1]
    total = int(temp_list[1]) + int(temp_list[2]) + int(temp_list[3])
    average = round(int(total) / 3.0, 2)
    temp_list.append(total)
    temp_list.append(average)
    final.append(temp_list)

print(tabulate(final, headers=["Name", "Lap1", "Lap2", "Lap3", "In Total", "Average"]))

Above code will give the following output:

enter image description here

Anuj Panchal
  • 391
  • 3
  • 15
  • also, is it possible to accomplish this without using external libraries? – Jay Jun 28 '22 at 11:11
  • I was aware of tabulate as I had used it previously. There maybe other ways to do it without using tabulate. If the tabulate answer helped you then kindly upvote and accept the answer :) – Anuj Panchal Jun 28 '22 at 11:23