【问题标题】:Go to next iteration after finding string by looping through text file?通过遍历文本文件找到字符串后进入下一次迭代?
【发布时间】:2015-10-15 02:51:37
【问题描述】:

我正在尝试遍历这样组织的文本文件:

学生 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.")

【问题讨论】:

    标签: python for-loop file-io iteration


    【解决方案1】:
     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)
    

    【讨论】:

    • 但我相信他想在检测到的学生姓名后面换行。
    • @digitaLink if 子句只有在找到学生姓名时才为真,操作数 in 进行检查 ....
    • 但是脚本中更改的行将是带有学生姓名的行。他想在下一行更改学生的成绩。
    • @digitaLink 你是对的!感谢您的评论,我已经更新了我的答案。
    • @digitaLink 非常感谢!我现在可以成功地隔离那条线。但现在我不知道如何改变它。 next(gradebook) = newValue 似乎没有任何改变。我该如何解决这个问题?
    【解决方案2】:

    一种方法是在 if 语句中将标志设置为 true,然后在下一次迭代中检查标志。更改成绩后,将标志设置回false。

    您还需要将每一行附加到一个变量中,以便在完成后将它们写回一个新文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-01
      • 2016-07-21
      • 1970-01-01
      • 2015-07-29
      • 2017-04-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多