解决Python往文件中插入多行字符串时的一个小问题

用Apache搭了一个最简单的Http服务器,每一次自动化脚本跑完之后要往http服务器的首页insert一条记录。
截图:
ee-auto-report

往Html源文件插入一行的代码如下所示:

def modify_index_html(apache_dir, log_path):
    """
    Function:Update the index.html to reflect the run result to the overall report
    @apache_dir: Apache http server folder:"C:\\Program Files (x86)\\Apache Software Foundation\\Apache2.2\\htdocs\\"
    @log_path: the path to the log generated in this run
    """
    logger.info("Updating " + apache_dir + "index.html")
    html = file(apache_dir + "index.html", "r")
    lines = []
    for line in html:
        lines.append(line)
    html.close()
    report_date = time.strftime('%Y-%m-%d', time.localtime(time.time()))
    status = get_report_run_status(report_generated_path)[1]   
    report_link = http_host_address + "/" + today_date + "/" + get_latest_result_folder(report_generated_path) \
        + "/" + "testresult.html"
    report_title = today_date + "-report"
    log_name = os.path.split(log_path)[1]
    log_link = http_host_address + "/" + today_date + "/" + get_latest_result_folder(report_generated_path) \
    + "/log/" + log_name
    insert_content = """        <tr>
            <td style="width: 183px; text-align: center;">%(suite)s</td>
            <td style="width: 195px;text-align: center;">%(date)s</td>
            <td style="width: 131px;text-align: center;color: red;"><strong>%(stat)s</strong></td>
            <td style="width: 165px;text-align: center;"><a id="report_link" href=%(rep_link)s>%(rep_title)s</a></td>
            <td style="width: 117px; text-align: center;"><a id="log_link" href=%(log_li)s>log</td>
        </tr>
    """ % {"suite": test_suite_name, "date": report_date, "stat": status, "rep_link": report_link, "rep_title": \
            report_title, "log_li": log_link}
    lines.insert(-4, insert_content)
    s = ''.join(lines)
    new_html = file(apache_dir + "index.html", "w")
    new_html.write(s)
    new_html.close()

运行多次之后观察发现,上面的这个insert每次都会在HTML源文件的末尾额外插入几个空格,导致HTML源文件中最后一行越来月长,解决的办法是在多行字符串后面添加"\n"并且不要回车。

    insert_content = """        <tr>
            <td style="width: 183px; text-align: center;">%(suite)s</td>
            <td style="width: 195px;text-align: center;">%(date)s</td>
            <td style="width: 131px;text-align: center;color: red;"><strong>%(stat)s</strong></td>
            <td style="width: 165px;text-align: center;"><a id="report_link" href=%(rep_link)s>%(rep_title)s</a></td>
            <td style="width: 117px; text-align: center;"><a id="log_link" href=%(log_li)s>log</td>
        </tr>\n""" 

Comments !