Search code examples
pythonpython-3.xstartswithends-with

How to print portion of the string from 'startswith' till 'endswith'


I like to save portions of the original text file, which can be identified in between 'startswith' and 'endswith' strings, into a new text file.

Example: The input text file contains following lines:

...abc…
...starts with string...
...def...
...ends with string...
...ghi...

...jkl...
...starts with string...
...mno...
...ends with string...
...pqr...

I am interested to extract the following lines into output text file:

starts with string...def...ends with string
starts with string...mno...ends with string

My following code returns empty list [ ]. Please help correct my code.

with open('file_in.txt','r') as fi:
    id = []
    for ln in fi:
        if ln.startswith("start with string"):
            if ln.endswith("ends with string"):
                id.append(ln[:])
                with open(file_out.txt, 'a', encoding='utf-8') as fo:
                    fo.write (",".join(id))
print(id)

I expect the file.out.txt to contain, all strings which start with the "start with string" and end with the "ends with string".


Solution

  • At the end of each line there is a character to tell the computer to show a new row. I am assuming here that "start with string" and "ends with string" are on the same line. If this is not the case add --"id.append(ln[:])"-- directly below the first if statement.

    Try

    ln.endswith("ends with string"+'\n' )
    

    or

    ln.endswith("ends with string"+'\n' +'\r')
    
    with open('C:\\Py\\testing.txt','r') as fi:
        id = []
        x = 0
        copy_line = False
        for ln in fi:
            if "starts with string" in ln:
                copy_line = True
            if copy_line:
                id.append ( ln[:] )
            if "ends with string" in ln :
                copy_line = False
    
        with open ('C:\\Py\\testing_out.txt', 'a', encoding='utf-8' ) as fo:
            fo.write (",".join(id))
    
    print(id)