下面是一个仅使用csv库的概念的快速示例(您当然可以优化很多这方面的内容,但它应该适用于示例)。在import csv
student_grades = []
# First open up your file containing the raw student grades
with open("studentGradeFrom.csv", "r") as file:
# Setup your reader with whatever your settings actually are
csv_file = csv.DictReader(file, delimiter=",", quotechar='"')
# Cycle through each row of the csv file
for row in csv_file:
# Calculate the numerical grade of the student
grade = grader(
int(row["test1"]),
int(row["test2"]),
int(row["test3"]),
int(row["test4"])
)
# Calculate the letter score for the student
score = gradeScores(grade)
# Assemble all the data into a dictionary
# Only need to save fields you need in the final output
student_grades.append({
"first_name": row["first_name"],
"last_name": row["last_name"],
"test1": row["test1"],
"test2": row["test2"],
"test3": row["test3"],
"test4": row["test4"],
"grade": grade,
"score": score
})
# Open up a new csv file to save all the grades
with open("studentGradeFrom.csv", "w", newline="") as file:
# List of column names to use as a header for the file
# These will be used to match the dictionary keys set above
# Only need to list the fields you saved above
column_names = [
"first_name", "last_name", "test1", "test2", "test3",
"test4", "grade", "score"
]
# Create the csv writer, using the above headers
csv_file = csv.DictWriter(file, column_names)
# Write the header
csv_file.writeheader()
# Write each dictionary to the csv file
for student in student_grades:
csv_file.writerow(student)
您需要根据您的具体要求对其进行微调,但希望它能让您朝着正确的方向前进。如果您需要一个特定的引用:https://docs.python.org/3.6/library/csv.html,那么大部分都会记录在官方文档中。在