python - 通过循环文本文件找到字符串后进入下一次迭代?

标签 python for-loop file-io iteration

我正在尝试迭代组织如下的文本文件:

学生 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/

相关文章:

objective-c - 将 NSMutableArray 写入文件并将其加载回来

使用 beautifulsoup 进行 Python 网络抓取 - 无法从 Clinicaltrials.gov 中提取首席研究员

python - 带时区的时间戳,使用 django ORM 未知

python - 在使用 `types.new_class` 创建的类上设置模块

javascript - 将字符串元素传递给数据键

c++ - 无法使用 ifstream::open 打开 html 资源文件 - Visual Studio 2013

java - 在读取和写入文件时避免丢失换行符 (\n)

python - numpy.linalg.det 的时间复杂度是多少?

Python 'for loop' 解析结果

javascript - 对于循环 getFileById() 抛出错误 : "No item with the given ID could be found....."