简体   繁体   English

如果前一行中的值匹配,如何让 Python 跳过读取 a.txt 文件中的一行

[英]How to get Python to skip reading a line in a .txt file if a value in the previous line matches

I'm a school administrator trying to write up a simple program that will help us identify when a student has a student program end date that has expired and needs to be renewed.我是一名学校管理员,试图编写一个简单的程序,以帮助我们确定学生的学生计划结束日期何时已过期且需要更新。 Here is a sample of a.txt file Python will read (fake student data and FERPA safe).这是一个 .txt 文件示例 Python 将读取(假学生数据和 FERPA 安全)。

101321654RIEP*20211226IP13

101321654RIEP*20200215IP13

200500106RIEP*20200630IP13

The first 9 digits are the student number.前 9 位数字是学号。 So the first two lines are the same student.所以前两行是同一个学生。 The third line is another student.第三行是另一个学生。 The 8 digits after the asterisk is the program expiration date.星号后的 8 位数字是程序到期日期。 So since the 1st student has a current program that is not expired, the second line is irrelevant and I need Python to disregard it (because the student's program was already renewed) and move onto the next student.因此,由于第一个学生的当前计划尚未过期,因此第二行无关紧要,我需要 Python 忽略它(因为学生的计划已经更新)并转移到下一个学生。

Where I'm struggling is in trying to tell Python "if you see the same student number as the previous line, skip over it and read the next one".我苦苦挣扎的地方是试图告诉 Python “如果您看到与上一行相同的学号,请跳过它并阅读下一个”。 Any guidance is much appreciated!非常感谢任何指导!

If your student list is not ordered by expiration date, a more robust solution would be to:如果您的学生列表未按到期日期排序,则更可靠的解决方案是:

  1. Keep a mapping of student information to their latest expiry date将学生信息映射到他们的最新到期日期
  2. Go through the mapping and renew the relevant entries. Go 通过映射更新相关条目。

Note that I'm keeping the date as a string for simplicity purposes.请注意,为简单起见,我将日期保留为字符串。

TODAY = "20210415"

with open(“your_file.txt”, “r”) as f:
    student_number_to_latest_expiry_date = {}
    for line in f:
        student_number = line[:9]
        expiry_date = line[-12:-4]
        existing_expiry_date = student_number_to_latest_expiry_date.get(student_number, None)
        if existing_expiry_date is None or expiry_date > existing_expiry_date:
            student_number_to_latest_expiry_date[student_number] = expiry_date

    for student_number, expiry_date in student_number_to_latest_expiry_date.items():
        if expiry_date < TODAY:
            print(f"need to renew for student #{student_number}")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM