Python : select 文本中的特定行

Python : select a specific line from text

我正在尝试编写一个代码:

如果是 = 打印“ok”:

str1 = "Start"

with open("C:...test.txt") as file:
for line in file:
    if str1 in line:
        if "contain" in line:
            print "OK"
        else:
            print "NOK"

我需要整合“第 3 行”条件

可能开销很小,但如果您的文件不是太大,我会转储列表 L 中的每一行,然后循环遍历该列表 - 如果行 r 以 str1 开头,您可以只执行 L [r+3] 并检查它是否包含 'contain'.

使用两个列表来存储符合您的规则的位置。

然后检查位置是否与您的相对偏移相匹配。

start_lines = []
contains_lines = []
with open("C:...test.txt") as inp:
    line_num = 0
    for line in inp:
        if line.startswith("start"):
            start_lines.append(line_num)

        if "contains" in line:
            contains_lines.append(line_num)

        line_num += 1

print [line_num for line_num in contains_lines if line_num - 3 in start_line]

为了更好地使用内存,您可以使用枚举来跟踪行号:

str1 = "Start"
fp = open("C:...test.txt")
check = 0
for i,line in enumerate(fp):
    if str1 in line:
        check = i
        continue
    if "contain" in line and (i == check + 3):
        print "OK"
    else:
        print "NOK"

此处 i == check + 3 condition 将检查您的第 3 行条件。

@Mehdi ouahabi 你提出 "go to the line that start with Start",所以我们只检查以 "Start" 开头的行,而不检查包含 Start[=20 的行=]在中间或末尾:

with open("test.txt") as file:
    for line in file:
        if line.startswith("Start"): #instead of "str1 in line" 
            if "contain" in line: print "OK"
            else: print "NOK"

***编辑:***在这种情况下,您将检查一行是否开始/包含今天的日期

from datetime import date
with open("test.txt") as file:
    for line in file:
       #if str(date.today()) in line:#check if today's date exist in the line
       if line.startswith(str(date.today())): #check if the line start with today's dates
            if "contain" in line: print "OK"
            else: print "NOK"