如何使用python在html文件的中间插入一行代码?

时间:2018-07-04 08:30:41

标签: python-3.x

我有一个名为Hello.html的html文件,

Hello.html

tb = TensorBoard('log_dir')
model.fit(x_train, y_train,
          epochs=20,
          batch_size=128,
          callbacks=[tb])

我希望添加几行

<html>
<head>
<title>Window Title or Email Subject</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!--@SPF-JS-HEADER@-->
<body>
<p>Hello</p>
</body>
</html>

所以我希望使用python代码,只需插入样式脚本和如下所示的输出:

<style type="text/css">
table.tblin, td.tblin, th, td.alt 
{
     border-color:#cc9;
     border-collapse:collapse;
     border-style:solid;
     border-width:1px;
     border-spacing:4px;
}

有人有主意吗?

1 个答案:

答案 0 :(得分:1)

a = """<style type="text/css">
table.tblin, td.tblin, th, td.alt
{
     border-color:#cc9;
     border-collapse:collapse;
     border-style:solid;
     border-width:1px;
     border-spacing:4px;
}
"""    # make a string of your required text to be appended

with open('train.html', 'r+') as f:
    lines = f.readlines()
    for i, line in enumerate(lines):
        if line.startswith('<!--@SPF-JS-HEADER@-->'):   # find a pattern so that we can add next to that line
            lines[i] = lines[i]+a
    f.truncate()
    f.seek(0)                                           # rewrite into the file
    for line in lines:
        f.write(line)