[Solved] Delete lines from text file – python [closed]


This answer is assuredly overkill for your simple line selection problem, but it illustrates a nice property of Python: Often a very generalized pattern of behavior or processing can be very generally stated in a way that goes well beyond the original use case. And instead of creating a one-time tool, you can create very flexible, highly reusable meta-tools.

So without further ado, a generator for returning only the lines of a file bounded by two terminal strings, and with a generalized preprocessing facility:

import os

def bounded_lines(filepath, start=None, stop=None,
                  preprocess = lambda l: l[:-1]):
    """
    Generator that returns lines from a given file.
    If start is specifed, emits no lines until the
    start line is seen. If stop is specified, stops
    emitting lines after the stop line is seen.
    (The start and stop lines are themselves emitted.)
    Each line can be pre-processed before comparison
    or yielding. By default, this is just to strip the
    final character (the newline or \n) off. But you
    can specify arbitrary transformations, such as
    stripping spaces off the string, folding its case,
    or just whatever.
    """
    preprocess = lambda x: x if preprocess is None else preprocess
    filepath = os.path.expanduser(filepath)
    with open(filepath) as f:
        # find start indicator, yield it
        for rawline in f:
            line = preprocess(rawline)
            if line == start:
                yield line
                break
        # yield lines until stop indicator found, yield
        # it and stop
        for rawline in f:
            line = preprocess(rawline)
            yield line
            if line == stop:
                raise StopIteration


for l in bounded_lines('test.txt', 'DOCHELLO', 'SIRFORHE'):
    print l

2

solved Delete lines from text file – python [closed]