MST

星途 面试题库

面试题:Python文件操作里if语句复杂条件控制实现

现有一个包含学生成绩信息的CSV文件,格式为姓名,语文成绩,数学成绩,英语成绩。使用Python编写程序,通过if语句判断,将总分大于240分且每科成绩都不低于70分的学生信息,写入到另一个新的文件中。
20.4万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import csv


with open('students_scores.csv', 'r', encoding='utf-8') as infile:
    reader = csv.reader(infile)
    headers = next(reader)
    with open('qualified_students.csv', 'w', encoding='utf-8', newline='') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(headers)
        for row in reader:
            name = row[0]
            chinese_score = int(row[1])
            math_score = int(row[2])
            english_score = int(row[3])
            total_score = chinese_score + math_score + english_score
            if total_score > 240 and chinese_score >= 70 and math_score >= 70 and english_score >= 70:
                writer.writerow(row)