如何在txt fi上以表格格式显示数据

2024-05-29 04:26:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经被这个python问题困扰了好几个小时。我试图找出如何将上面可以手动输入的数据写入到一个txt文件中,使其显示在一个两行八列的表中。name_数组中的内容应该是头,data_数组中的内容是实际的数据片段。在

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

Tags: ofthenameinputrawfloatscoreenter
2条回答

你有没有试过:

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')

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

import csv

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

它将输出:

^{pr2}$

在这个例子中,使用tabs作为分隔符,但是您可以用任何字符来替换它。有关更多选项,请参见this documentation。在


相反,如果您想要更具可读性的内容,可以使用intead 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以获取格式化表的更多选项。在

相关问题 更多 >

    热门问题