简体   繁体   中英

Search and replace previous line python

In a file I have the following text:

 xxxxxx
    PCTFREE    10
    INITRANS   8
    MAXTRANS   255
    STORAGE    (
                BUFFER_POOL      DEFAULT
               ),
)

I am trying to search for line that startswith(")") and remove the "," from the previous line.

with open('filename') as f:
    print(f.read().replace(',\n)','\n)')

What you're asking for in your description doesn't match anything in your sample input, or even come close to it. None of your lines starts with ) . One of your lines starts with some whitespace and a ), but the line before that is a blank line, and the last non-blank line before that doesn't have a comma anywhere to remove.

But I'll ignore the sample input and explain how to do what you were asking for in the description.

The simplest way is to just keep track of the previous line while iterating the lines:

lastline = None
for line in infile:
    line = line.rstrip()
    if line.startswith(")"):
        if lastline is not None:
            lastline = lastline.rstrip(",")
    if lastline is not None:
        outfile.write(lastline + '\n')
    lastline = line
if lastline is not None:
    outfile.write(lastline + '\n')

You can make this a little cleaner and more compact by using a pairwise iterator wrapper like the one in the itertools recipes , but slightly modified to include the "extra" pair at the end:

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.zip_longest(a, b, fillvalue='')

stripped = (line.rstrip() for line in infile)
for line, nextline in pairwise(stripped):
    if nextline.startswith(")"):
        line = line.rstrip(",")
    if line is not None:
        outfile.write(line + '\n')

You can loop over the text line by line and check one index ahead for a ) :

new_s = [i.strip('\n') for i in open('filename.txt')]
final_data = '\n'.join(new_s[i][:-1] if new_s[i+1].startswith(')') else new_s[i] for i in range(len(new_s)-1))

Output:

xxxxxx
PCTFREE    10
INITRANS   8
MAXTRANS   255
STORAGE    (
        BUFFER_POOL      DEFAULT
       )
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM