Python Extract Text between two strings into Excel
<p>I have a text file like this</p>

<pre><code>blablablabla
blablablabla
Start
Hello
World
End
blablabla
</code></pre>

<p>I want to extract the strings between Start and End and write them into an Excel cell. My code thus far looks like this:</p>

<pre><code>import xlsxwriter
workbook = xlsxwriter.Workbook("Test1.xlsx")
worksheet = workbook.add_worksheet()

flist = open("TextTest.txt").readlines()

parsing = False
for line in flist:

    if line.startswith("End"):
       parsing = False
    if parsing:
       worksheet.write(1,1,line)
    if line.startswith("Start"):
       parsing = True

workbook.close()
</code></pre>

<p>However it returns only an empty workbook. What am I doing wrong?</p>

<p>The data is being written to the cell, but one problem is that <code>worksheet.write()</code> will overwrite the contents of the cell, so only the last item written will be present.</p>

<p>You can solve this by accumulating the lines between <code>Start</code> and <code>End</code> and then writing them with one <code>worksheet.write()</code>:</p>

<pre><code>import xlsxwriter

workbook = xlsxwriter.Workbook("Test1.xlsx")
worksheet = workbook.add_worksheet()

with open("TextTest.txt") as data:
    lines = []
    for line in data:
        line = line.strip()
        if line == "Start":
           lines = []
        elif line == "End":
            worksheet.write(0, 0, '\n'.join(lines))

workbook.close()
</code></pre>

<p>Here lines are accumulated into a list. When an end line is seen the contents of that list are joined with new lines (you could substitute this for another character, e.g. space) and written to the cell.</p>

python excel text