编写一个可查询,修改,删除,添加信息的程序,要能够储存学号,姓名,家庭住址,联系电话等信息
时间: 2024-04-28 07:23:57 浏览: 58
好的,我来为您解答这个问题。这个程序可以使用 Python 语言来编写,主要使用文件操作来实现信息的储存和修改。以下是一个简单的示例代码:
```python
import os
class Student:
def __init__(self, id, name, address, phone):
self.id = id
self.name = name
self.address = address
self.phone = phone
class StudentDB:
def __init__(self, filename):
self.filename = filename
self.students = []
self.load()
def load(self):
if not os.path.exists(self.filename):
return
with open(self.filename, 'r') as file:
for line in file:
id, name, address, phone = line.strip().split(',')
self.students.append(Student(id, name, address, phone))
def save(self):
with open(self.filename, 'w') as file:
for student in self.students:
file.write(f"{student.id},{student.name},{student.address},{student.phone}\n")
def add_student(self, id, name, address, phone):
self.students.append(Student(id, name, address, phone))
self.save()
def update_student(self, id, name, address, phone):
for student in self.students:
if student.id == id:
student.name = name
student.address = address
student.phone = phone
self.save()
return True
return False
def delete_student(self, id):
for i, student in enumerate(self.students):
if student.id == id:
del self.students[i]
self.save()
return True
return False
def search_student(self, id):
for student in self.students:
if student.id == id:
return student
return None
def get_all_students(self):
return self.students
```
上述代码中,`Student` 类用于储存单个学生的信息,`StudentDB` 类用于储存所有学生的信息,包括从文件中读取和写入信息的方法。可以使用以下代码来测试:
```python
db = StudentDB('students.txt')
db.add_student('001', 'Tom', 'Beijing', '123456789')
db.add_student('002', 'Jerry', 'Shanghai', '987654321')
db.update_student('002', 'Jerry', 'Nanjing', '987654321')
db.delete_student('001')
print(db.get_all_students())
print(db.search_student('002'))
```
这个程序可以储存学号、姓名、家庭住址、联系电话等信息,并且支持添加、修改、删除和查询学生信息。
阅读全文