如何在txt文件中以表格格式显示数据

时间:2016-10-06 18:27:34

标签: python file tabular

我被困在这个python问题上好几个小时。我试图弄清楚如何将上面手动输入的数据写入txt文件,其方式显示在两行八列表中。 name_array中的内容应该是标题,data_array中的内容是实际的数据。

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"]

2 个答案:

答案 0 :(得分:1)

如果您只想输出类似csv的文件,可以使用csv包:

import csv

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

将输出:

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

在此示例中,使用tab作为分隔符,但您可以使用您想要的任何字符进行拼写。有关更多选项,请参阅this documentation

相反,如果你想要一些更易读的东西,你可以使用tabulate包:

from tabulate import tabulate

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

它会产生:

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

有关格式化表格的更多选项,请参阅this documentation

答案 1 :(得分:-1)

你有没有试过像:

output_file = 'out.txt'
with open(output_file, 'r+') as file:
    file.write('\t'.join(name_array) + '\n')
    file.write('\t'.join(data_array) + '\n')