How to check for EOF in Python?

前端 未结 5 2435
深忆病人
深忆病人 2021-02-15 16:54

How do I check for EOF in Python? I found a bug in my code where the last block of text after the separator isn\'t added to the return list. Or maybe there\'s a better way of ex

5条回答
  •  粉色の甜心
    2021-02-15 17:37

    This is the standard problem with emitting buffers.

    You don't detect EOF -- that's needless. You write the last buffer.

    def get_text_blocks(filename):
        text_blocks = []
        text_block = StringIO.StringIO()
        with open(filename, 'r') as f:
            for line in f:
                text_block.write(line)
                print line
                if line.startswith('-- -'):
                    text_blocks.append(text_block.getvalue())
                    text_block.close()
                    text_block = StringIO.StringIO()
             ### At this moment, you are at EOF
             if len(text_block) > 0:
                 text_blocks.append( text_block.getvalue() )
             ### Now your final block (if any) is appended.
        return text_blocks
    

提交回复
热议问题