如何在Python中检查EOF?

2024-05-23 14:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python中检查EOF?我在代码中发现一个错误,分隔符之后的最后一段文本没有添加到返回列表中。或者也许有更好的方法来表达这个函数?

这是我的代码:

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()
    return text_blocks

Tags: 方法函数代码text文本列表def错误
3条回答

您可能会发现使用itertools.groupby解决这个问题更容易。

def get_text_blocks(filename):
    import itertools
    with open(filename,'r') as f:
        groups = itertools.groupby(f, lambda line:line.startswith('-- -'))
        return [''.join(lines) for is_separator, lines in groups if not is_separator]

另一种方法是使用regular expression来匹配分隔符:

def get_text_blocks(filename):
    import re
    seperator = re.compile('^-- -.*', re.M)
    with open(filename,'r') as f:
        return re.split(seperator, f.read())

这是发出缓冲区的标准问题。

你没有检测到EOF——那是不必要的。你写最后一个缓冲区。

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

只要for语句终止,文件结束条件就保持不变——这似乎是minory修复此代码的最简单方法(如果要在追加前检查它是否为空,可以在结尾提取text_block.getvalue())。

相关问题 更多 >