Adding Characters to beginning and end of line that matches expression (Python)
<p>Background: I am tasked with taking content from one website (mostly HTML tables), and inserting it into a wiki type site. I am able to poll the content (it is dynamic) using a REST API and get HTML formatted output. I must take this output, and convert it into Wiki Markup in order to then insert it into the new site. I am having issues with the conversion part.</p>

<p>Currently I am using the html2text module in my test script as below:</p>

<pre><code>import os
import sys
import html2text

file = raw_input("File to convert: ")

h = html2text.HTML2Text()
with open(file, 'r') as f:
    dataContent = f.read()
    dataConverted = h.handle(dataContent)

with open('tempconvert', 'w') as f:
    f.write(dataConverted)
    #print dataConverted

# Add the | to the line beginnings and endings

with open('tempconvert', 'r') as f:
    tempContent = f.readlines()

with open('finalconvert', 'w') as f:
    for line in tempContent:
        if '|' in line:
            f.write('|' + line.rstrip('\n') + '| \n')
</code></pre>

<p>Now, the reason for all this input and output is because the html2text module doesn't insert a beginning or trailing "|" which the wiki syntax needs to recognize it as a table. </p>

<p>My questions are:</p>

<ol>
<li>This is super ugly ... any way to clean this up without writing to so many temporary files?</li>
<li>When I use the final search for adding the "|", it only writes the lines it acts upon (which makes sense given the arguments). How would I get it to act upon those lines, but also keep all the other lines that it doesn't act upon?</li>
<li>It would also be awesome for me to be able to take the first line in the table instance (you can tell this because of whitespace before and after the table) and append a "||" in order to signify its a header row. Is this also possible?</li>
</ol>

<p>A first try:</p>

<pre><code>html = html2text.HTML2Text()
input_file = raw_input('File to convert: ')

with open(input_file, 'r') as input_, open('finalconvert', 'w') as output_:
    data = input_.read()
    data_converted = html.handle(data)

    for line in data_converted.split('\n'):
        if '|' in line:
            line = "|{}|\n".format(line.rstrip())
        output_.write(line.encode())
</code></pre>

<p>This code fixes 1 and 2; but I do not understood 3.</p>

python