這應該是一個開始給你:
started = False
collected_lines = []
with open(path, "r") as fp:
for i, line in enumerate(fp.readlines()):
if line.rstrip() == "Start":
started = True
print "started at line", i # counts from zero !
continue
if started and line.rstrip()=="End":
print "end at line", i
break
# process line
collected_lines.append(line.rstrip())
的enumerate
發電機以一個生成器和枚舉迭代。例如,
print list(enumerate("a b c".split()))
打印
[ (0, "a"), (1,"b"), (2, "c") ]
UPDATE:
海報要求使用正則表達式匹配線,如 「===」 和 「==」:
import re
print re.match("^=+$", "===") is not None
print re.match("^=+$", "======") is not None
print re.match("^=+$", "=") is not None
print re.match("^=+$", "=abc") is not None
print re.match("^=+$", "abc=") is not None
這個問題是非常相似,這一個http://stackoverflow.com/questions/7098530/repeatedly-extract-a-line-between-two-delimiters-in-a-text-file-python – salomonvh