-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathstudents.py
More file actions
39 lines (30 loc) · 896 Bytes
/
students.py
File metadata and controls
39 lines (30 loc) · 896 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import json
# 读取 JSON 文件
with open('students.json', 'r') as file:
students = json.load(file)
print(students)
# 遍历学生列表
for student in students:
name = student['name']
courses = student['courses']
print(f"Student: {name}")
print("Courses:")
for course in courses:
print(f" - {course}")
# 添加新学生
new_student = {
"name": "Charlie",
"age": 24,
"courses": ["Art", "Design"]
}
students.append(new_student)
# 将更新后的数据写回到 JSON 文件
with open('students.json', 'w') as file:
json.dump(students, file, indent=4)
print("New student added.")
# 删除名为 "Bob" 的学生
students = [student for student in students if student['name'] != 'Bob']
# 将更新后的数据写回到 JSON 文件
with open('students.json', 'w') as file:
json.dump(students, file, indent=4)
print("Student 'Bob' deleted.")