我在阅读特定行时遇到问题。它类似于这里回答的问题: python - Read file from and to specific lines of text 不同的是,我没有固定的结束标记。让我举个例子:
--------------------------------
\n
***** SOMETHING ***** # i use this as my start
\n
--------------------------------
\n
data of interest
data of interest
data of interest
\n
----------------------- #this will either be dashes, or EOF
***** SOMETHING *****
-----------------------
我尝试过类似上面的链接,但我不能创建一个if语句来打破循环,因为我不知道它是不是EOF。
答案 0 :(得分:0)
这个怎么样:
def getBlocks(filepath):
with open(filepath) as f:
blocks = []
go = False
for line in f:
if line.strip() == startDelimiter:
block = ''
go = True
if go:
block += line
if line.strip() == endDelimiter:
blocks.append(block)
block = ''
go = False
if block:
blocks.append(block)
return blocks
答案 1 :(得分:0)
美丽的是,如果你点击EOF,文件将停止迭代。
ended = False
for line in f:
ended = line == MY_END_MARKER
答案 2 :(得分:0)
你能不能做到
parts = my_file.read().split("-----------------------")
print parts