写一个基于python的宿舍管理系统代码
时间: 2024-05-02 21:23:53 浏览: 115
好的,以下是一个简单的基于Python的宿舍管理系统代码:
```python
import csv
# 定义学生类
class Student:
def __init__(self, name, gender, age, room):
self.name = name
self.gender = gender
self.age = age
self.room = room
def __str__(self):
return f"{self.name}, {self.gender}, {self.age}, {self.room}"
# 定义宿舍管理系统类
class Dormitory:
def __init__(self, file_name):
self.file_name = file_name
self.students = []
# 读取CSV文件中的学生信息
def load_students(self):
with open(self.file_name, "r") as file:
reader = csv.reader(file)
for row in reader:
student = Student(row[0], row[1], row[2], row[3])
self.students.append(student)
# 添加学生
def add_student(self, student):
self.students.append(student)
# 删除学生
def remove_student(self, student):
self.students.remove(student)
# 根据房间号查询学生
def search_student(self, room):
result = []
for student in self.students:
if student.room == room:
result.append(student)
return result
# 保存学生信息到CSV文件中
def save_students(self):
with open(self.file_name, "w", newline="") as file:
writer = csv.writer(file)
for student in self.students:
writer.writerow([student.name, student.gender, student.age, student.room])
# 测试代码
if __name__ == "__main__":
dorm = Dormitory("students.csv") # 创建宿舍管理系统对象
dorm.load_students() # 读取学生信息
print("学生信息:")
for student in dorm.students:
print(student)
# 添加学生
dorm.add_student(Student("张三", "男", 18, "101"))
dorm.add_student(Student("李四", "女", 19, "101"))
print("添加学生后的信息:")
for student in dorm.students:
print(student)
# 删除学生
dorm.remove_student(Student("张三", "男", 18, "101"))
print("删除学生后的信息:")
for student in dorm.students:
print(student)
# 查询学生
result = dorm.search_student("101")
print("查询结果:")
for student in result:
print(student)
# 保存学生信息
dorm.save_students()
```
这个代码定义了一个学生类和宿舍管理系统类,通过读取CSV文件来管理学生信息。你可以根据具体需求修改代码。
阅读全文