How to check for EOF in Python?

前端 未结 5 2432
深忆病人
深忆病人 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:16

    Why do you need StringIO here?

    def get_text_blocks(filename):
        text_blocks = [""]
        with open(filename, 'r') as f:
            for line in f:
                if line.startswith('-- -'):
                    text_blocks.append(line)
                else: text_blocks[-1] += line          
        return text_blocks
    

    EDIT: Fixed the function, other suggestions might be better, just wanted to write a function similar to the original one.

    EDIT: Assumed the file starts with "-- -", by adding empty string to the list you can "fix" the IndexError or you could use this one:

    def get_text_blocks(filename):
        text_blocks = []
        with open(filename, 'r') as f:
            for line in f:
                if line.startswith('-- -'):
                    text_blocks.append(line)
                else:
                    if len(text_blocks) != 0:
                        text_blocks[-1] += line          
        return text_blocks
    

    But both versions look a bit ugly to me, the reg-ex version is much more cleaner.

提交回复
热议问题