程序功能:统计学生Python课程成绩 读取CSV文件(文本格式)student_score.csv中所有的行,每行包含了学生学号,姓名及Python成绩(有列名),如下: 学号,姓名,Python 202203,张三,90 202209,李四,88 202218,王五,79 ……,……,…… 计算所有学生Python成绩的平均分和中位数,把统计结果写入文本文件result.txt中。
时间: 2024-02-22 11:57:04 浏览: 24
以下是Python代码实现:
```python
import csv
import statistics
# 读取CSV文件
with open("student_score.csv", "r", encoding="utf-8") as f:
reader = csv.DictReader(f)
# 存储所有学生Python成绩
scores = []
for row in reader:
# 获取Python成绩
score = int(row["Python"])
scores.append(score)
# 计算平均分和中位数
avg_score = statistics.mean(scores)
median_score = statistics.median(scores)
# 将统计结果写入文本文件
with open("result.txt", "w", encoding="utf-8") as f:
f.write(f"平均分:{avg_score:.2f}\n")
f.write(f"中位数:{median_score}\n")
```
程序首先使用Python内置的csv模块读取CSV文件,并将所有学生Python成绩存储在列表中。然后使用statistics模块计算平均分和中位数。最后将结果写入文本文件result.txt中。
需要注意的是,CSV文件中的第一行为列名,可以通过csv.DictReader的方式读取,可以使用列名来获取Python成绩。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.png)