Splitting textfile into section with special delimiter line - python

前端 未结 3 1748
说谎
说谎 2020-12-19 14:58

I have an input file as such:

This is a text block start
This is the end

And this is another
with more than one line
and another line.

The

3条回答
  •  失恋的感觉
    2020-12-19 15:34

    How about pass a predicate?

    def per_section(it, is_delimiter=lambda x: x.isspace()):
        ret = []
        for line in it:
            if is_delimiter(line):
                if ret:
                    yield ret  # OR  ''.join(ret)
                    ret = []
            else:
                ret.append(line.rstrip())  # OR  ret.append(line)
        if ret:
            yield ret
    

    Usage:

    with open('/path/to/file.txt') as f:
        sections = list(per_section(f))  # default delimiter
    
    with open('/path/to/file.txt.txt') as f:
        sections = list(per_section(f, lambda line: line.startswith('#'))) # comment
    

提交回复
热议问题