通过遍历文本文件找到字符串后转到下一次迭代?
Go to next iteration after finding string by looping through text file?
我正在尝试遍历这样组织的文本文件:
学生 1 姓名
学生一年级
学生 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.")
一种方法是在 if 语句中将标志设置为 true,然后在下一次迭代中检查该标志。更改成绩后,将标志设置回 false。
您还需要将每一行附加到一个变量,以便在完成后将它们写回新文件。
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 姓名
学生一年级
学生 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.")
一种方法是在 if 语句中将标志设置为 true,然后在下一次迭代中检查该标志。更改成绩后,将标志设置回 false。
您还需要将每一行附加到一个变量,以便在完成后将它们写回新文件。
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)