我正在尝试迭代组织如下的文本文件:
学生 1 姓名
一年级学生
学生2姓名
2年级学生
...
学生N姓名
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.")
最佳答案
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)
关于python - 通过循环文本文件找到字符串后进入下一次迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33139017/