我正在尝试迭代这样组织的文本文件:
学生1姓名
学生1年级
学生2姓名
学生2年级
...
学生姓名
学生N年级
一旦我找到一个学生姓名,我怎样才能改变他的成绩?这是我提出的代码,但我无法弄清楚如何更改学生姓名后面的行。
gradebook = open('gradebook.txt', 'r')
studentName = input("What is the students name?")
for line in gradebook:
if line.rstrip() == studentName:
#I want to insert code here that would change the text on the line
#after the line where studentName is found.
else:
print("The student was not found.")
答案 0 :(得分:2)
temp = []
with open('data', 'r') as f:
for line in f:
if "Student 2" in line:
try:
# get Student 2 grade
line = next(f)
temp.append(changed_line)
# just in case Student name was the last line of the file
except StopIteration:
break
else:
temp.append(line)
# save you changes back to the file
with open('data', 'w') as f:
for line in temp:
f.write(line)
答案 1 :(得分:0)
一种方法是在if语句中将标志设置为true,然后在下一次迭代时检查标志。更改成绩后,将标志设置为false。
完成后,您还需要将每一行附加到变量,以便将它们写回新文件。