python代码:立如下的 学生信息文件,每行存入 学号、姓名、性别、 身高等信息,存为 student.txt 文件 ,读此文件,调用 学生类中的所有西数,进行数据 维护后,重新存回到文件 student.txt中。
时间: 2023-06-11 17:06:22 浏览: 75
以下是代码实现:
```python
class Student:
def __init__(self, id, name, gender, height):
self.id = id
self.name = name
self.gender = gender
self.height = height
def __str__(self):
return f"{self.id},{self.name},{self.gender},{self.height}"
def read_file(file_path):
students = []
with open(file_path, 'r') as file:
for line in file.readlines():
data = line.strip().split(',')
student = Student(data[0], data[1], data[2], data[3])
students.append(student)
return students
def write_file(file_path, students):
with open(file_path, 'w') as file:
for student in students:
file.write(str(student) + '\n')
def main():
file_path = 'student.txt'
students = read_file(file_path)
# 数据维护
for student in students:
student.height = float(student.height) + 10
write_file(file_path, students)
if __name__ == '__main__':
main()
```
首先定义了一个 `Student` 类,包含学号、姓名、性别、身高等属性,以及 `read_file` 和 `write_file` 函数用于读写文件。在 `main` 函数中,首先读取 `student.txt` 文件中的学生信息,然后对学生的身高属性进行数据维护,最后重新将更新后的学生信息写回到 `student.txt` 文件中。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)