.数据保存到文件中。 写一个程序能够把从键盘输入的学生成绩进行简单的总评计算后写入某个文件中,也能从已知的数据文件中,加载学生成绩进行简单的总评计算,再写到文件中。假设学生成绩数据包括学号、姓名、平时成绩、期中成绩和期末成绩。
时间: 2024-02-22 22:55:25 浏览: 79
好的,这是一个比较典型的文件读写操作,我可以为您提供一份示例代码,供您参考和学习。
首先,我们需要定义一个学生类,用于存储每个学生的信息:
```python
class Student:
def __init__(self, id, name, daily_score, midterm_score, final_score):
self.id = id
self.name = name
self.daily_score = daily_score
self.midterm_score = midterm_score
self.final_score = final_score
self.total_score = self.get_total_score()
def get_total_score(self):
return self.daily_score * 0.3 + self.midterm_score * 0.3 + self.final_score * 0.4
```
然后我们需要实现从键盘输入学生成绩并保存到文件中的功能:
```python
def save_scores_to_file(file_path):
students = []
while True:
id = input("请输入学号(输入0结束):")
if id == '0':
break
name = input("请输入姓名:")
daily_score = float(input("请输入平时成绩:"))
midterm_score = float(input("请输入期中成绩:"))
final_score = float(input("请输入期末成绩:"))
student = Student(id, name, daily_score, midterm_score, final_score)
students.append(student)
with open(file_path, 'w') as f:
for student in students:
f.write(f"{student.id},{student.name},{student.daily_score},{student.midterm_score},{student.final_score}\n")
print(f"学生成绩已保存到{file_path}文件中。")
```
接下来我们实现从文件中加载学生成绩并计算总评后再保存到文件中的功能:
```python
def load_scores_from_file(file_path):
students = []
with open(file_path, 'r') as f:
for line in f:
id, name, daily_score, midterm_score, final_score = line.strip().split(',')
student = Student(id, name, float(daily_score), float(midterm_score), float(final_score))
students.append(student)
return students
def calculate_and_save_scores(file_path):
students = load_scores_from_file(file_path)
for student in students:
student.total_score = student.get_total_score()
with open(file_path, 'w') as f:
for student in students:
f.write(f"{student.id},{student.name},{student.daily_score},{student.midterm_score},{student.final_score},{student.total_score}\n")
print(f"学生成绩已计算并保存到{file_path}文件中。")
```
最后我们可以提供一个主函数,让用户选择要进行的操作:
```python
def main():
file_path = 'scores.txt'
while True:
print("请选择要进行的操作:")
print("1. 从键盘输入学生成绩并保存到文件中")
print("2. 从文件中加载学生成绩并计算总评后再保存到文件中")
print("3. 退出程序")
choice = input("请输入选择的操作:")
if choice == '1':
save_scores_to_file(file_path)
elif choice == '2':
calculate_and_save_scores(file_path)
elif choice == '3':
break
else:
print("无效的选择,请重新输入。")
```
这样,我们就完成了一个简单的学生成绩保存和计算程序。当然,这只是一个示例,实际应用中可能还需要进行异常处理、数据校验等操作。
阅读全文