Python read specific lines of text

眉间皱痕 提交于 2019-12-25 16:09:17

问题


I am having a problem reading specific lines. It's similar to the question answered here: python - Read file from and to specific lines of text The difference, I don't have a fixed end mark. Let me show an example:

--------------------------------
\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 *****
-----------------------

I tried doing something similar to the above link, but I can't create a if statement to break the loop since I don't know if it will be the EOF or not.


回答1:


How about this:

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



回答2:


The beauty is that if you hit EOF, the file will stop iterating.

ended = False
for line in f:
    ended = line == MY_END_MARKER



回答3:


Couldn't you just do

parts = my_file.read().split("-----------------------")
print parts


来源:https://stackoverflow.com/questions/11729120/python-read-specific-lines-of-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!