How can I tabulate the data strings I have saved in another file...
the data sored is in the form of names and scores. The table should look like:

Name Score 1 Score 2 Score 3
==== ======= ======= =======

John 23 21 34
etc...

I've started with this and need help adapting it to produce a table and it needs to us the split function, explanations would be very useful too!:

def main():
f = open( "data_file_1.dat", "r" )
line = f.readline()
while len(line) !=0:
print line
line = f.readline()
main()


Help with the code?
Thanks in advance!

Recommended Answers

All 5 Replies

Could you attach a copy of data_file_1.dat to your post? Or if you could post some of the data (within code tags) it would make it easier to help you with this.

A better way to deal with text files is rather with for loop :

of=open(myoutfilename, 'w')
for line in open(myfilename,'r'):
    print line
    of.write(line.replace(' ', '\t'))
of.close()

######### OR ##############
# not sure the 2 with on the same line work (and i can't test it right now)
# this would be a preferred way (even if i use the first one)

with open(myfilename,'r') as f, with open(myoutfilename,'w') as of:
    for line in f:
        print line
        of.write(line.replace(' ', '\t'))

if replacing the spaces is enough in your case

ok, here's the data..., changed filetype to txt for uploading

You can expand on something simple like that ...

''' contents of data_file_1.txt -->
Fred, Nurke, 16, 17, 22
Jack, Sprat, 12, 13, 19
George, Reynolds, 14, 11, 30
Harry, Smith, 19, 19, 37
Daniel, Robins, 10, 8, 22
Jacquiline, Stevens, 23, 18, 31
Erin, Collins, 24, 30, 35
William, Steadford, 12, 15, 20
Laura, Schmidt, 25, 27, 36
Nikki, Dimitri, 14, 17, 24
'''

with open('data_file_1.txt', 'r') as fin:
    print("%-20s %5s %5s %5s" % ('name', 'score1', 'score2', 'score3'))
    for line in fin:
        # strip trailing newline char
        line = line.rstrip()
        first, last, score1, score2, score3 = line.split(',')
        name = first + last
        print("%-20s %5s %5s %5s" % (name, score1, score2, score3))

Neat coding vegaseat:

first, last, score1, score2, score3 = line.split(',')
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.