Search code examples
pythonfiletabular

How to display data in tabular format on a txt file


I have been stuck on this python problem for hours. I'm trying to figure out how to write the data that can be manually entered above into a txt file in a way that it shows up in a two row eight column table. The contents in name_array are supposed to be headers and the contents in data_array are the actual data pieces.

name = str(raw_input( "Enter the student's name: "))
medianScore = float(raw_input("Enter the median group score for quizzes:"))
indScore = float(raw_input("Enter the score of the individual quiz:  "))
assignmentScore = float(raw_input("Enter the score of the assignment: "))
test1Score = float(raw_input("Enter the score of exam one: "))
test2Score = float(raw_input("Enter the score of exam two: "))
test3Score = float(raw_input("Enter the score of the final exam: "))
fileName = str(raw_input("Enter the name of the file you would like to create: "))
f = file(fileName + ".txt" , a)

finalScore = ((medianScore * .14) + (indScore * .14) + (assignmentScore * .12) + (test1Score * .15) +(test2Score * .20) + (test3Score * .25))
data_array = [name, finalScore, test3Score, test1Score, test2Score, assignmentScore,  indScore, medianScore]
name_array = [ "Student", "Final Grade", "Final Exam", "Exam 1", "Exam 2", "Assignments", "Solo Quizzes", "Group Quizzes"]

Solution

  • If you want to simply output a csv-like file you can use the csv package:

    import csv
    
    writer = csv.writer(f, delimiter='\t')
    writer.writerow(name_array)
    writer.writerow(data_array)
    

    It will output:

    Student Final Grade Final Exam  Exam 1  Exam 2  Assignments Solo Quizzes    Group Quizzes
    asd 3.88    6   4   5   3   2   1
    

    In this example use tabs as separator, but you can cange it with any char you want. See this documentation for more options.


    Instead if you want something more human-readable you can use intead the tabulate package:

    from tabulate import tabulate
    
    f.write(tabulate([data_array], headers=name_array))
    

    It will produce:

    Student      Final Grade    Final Exam    Exam 1    Exam 2    Assignments    Solo Quizzes    Group Quizzes
    ---------  -------------  ------------  --------  --------  -------------  --------------  ---------------
    asd                 3.88             6         4         5              3               2                1
    

    See this documentation for more options to format your table.