Python Forum
Table with fixed columns
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Table with fixed columns
#1
I am trying to print a table from a file with fixed columns. I have the initial part down but I am not sure where to begin to break down the data into tables and columns?

raw data in the file is this
William,180, 1st place, 250, 390, 400
tim,182, 2nd place, 160, 380, 400
billy,187, 3rd place, 175, 325, 250
tom,185, 4th place, 150, 300, 200



#column are name, wt, place, deadlift, squat, benchpress

rfile = open("finishers.txt", "r")
file = rfile.readlines()


for line in file:
    values = line.split(',')
    print (values)
    




rfile.close()
Output:
desired out put Name WT Place Deadlift Squat Benchpress William 180 1st place 250 390 400 tim 182 2nd place 160 380 400 billy 187 3rd place 175 325 250 tom 185 4th place 150 300 200
Reply
#2
First you need to determine the column widths. Load the data into a list of lists. Then loop through it and determine the widest string in each column (include the column headers when doing this). Then decide how wide your gutter is (the space between columns).

The easy way to do this is with the format method of strings, or the even newer f-string syntax (Python 3.6+). There you can set the width of each field, and create a template for printing each line.

If that is not available because this is homework, loop through the lines. Print each column in that line, plus a number of spaces to fill out to the column width, plus a number of spaces for the gutter. Use the end = '' parameter to print to keep it going to the next line between columns, and then end the line with a plain print().
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Ok that is somewhat helpful. I have heard this list of list before but I have never done it from a txt or csv file. is there any documentation you can point me to how after I read the data to put it into a list of list?
Reply
#4
Using your code:

data = []
for line in file:
    values = line.split(',')
    data.append(values)
That will give you a list of lists. Then data[0] is the first row, and data[0][1] is the second item in the first row.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Extract columns from a 2 dimentional table Leyo 4 1,729 Feb-22-2022, 07:50 PM
Last Post: Leyo
  split the line fixed length tokens bb8 5 5,632 Nov-25-2017, 06:18 PM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020