我只是想知道如何删除我想在python中更改的学生的所有相关信息。谢谢你
这是我的app.py
# change student information
if choice == 2:
student_name = input("Please enter a student name that you want to change information:")
with open("student.txt", "r") as file:
lines = file.readlines()
update_line = []
found_student = False
for line in lines:
if line.startswith("Name: " + student_name):
student = Student(input("Please enter the updated student name: "), input("Please enter the updated student major: "), input("Please enter the updated student GPA: "))
update_line.append("Name: " + str(student.name) + "\n")
update_line.append("Major: " + str(student.major) + "\n")
update_line.append("GPA: " + str(student.gpa) + "\n")
update_line.append("On Probation: " + str(student.on_probation()) + "\n\n")
found_student = True
else:
update_line.append(line)
if found_student:
with open("student.txt", "w") as file:
file.writelines(update_line)
print("Successfully updated")
file.close()
else:
print("Failed to update or student not found.") `
user_options()
输出
Name: John
Major: IT
GPA: 1.9
On Probation: True
Name: Bunnie
Major: Hos
GPA: 3.6
On Probation: False
#I want to remove these as it was the old student information
Major: Art
GPA: 3.0
On Probation: False
Name: Johh Park
Major: Business
GPA: 2.0
On Probation: False
Name: Van Hien
Major: Art
GPA: 3.1
On Probation: False
我试着用循环来移除那个对象剩下的所有线条,但它只是移除了所有的线条
1条答案
按热度按时间q8l4jmvw1#
与调用
readlines()
将整个文件读入列表不同,直接使用for line in file:
循环文件。然后,您可以有一个内部循环来读取行,直到下一个空行为止,因此当您修改学生时,可以跳过剩余的行。正如在评论中提到的,像SQLite这样的数据库会让事情变得更容易。或者,您可以使用CSV文件,而不是为每个学生使用多行。或者使用JSON或Pickle将整个列表或字典写入文件。
一般来说,您应该决定该文件是供人类使用还是供计算机使用。相同的格式并不总是对两者都是最好的。