我有一个带有页眉和页脚的文件(html)模板。我尝试在<trbody>
之后插入文本。
我现在正在做的方式是使用fileinput.input()
def write_to_html(self,path):
for line in fileinput.input(path, inplace=1):
line = re.sub(r'CURRENT_APPLICATION', obj, line)
line = re.sub(r'IN_PROGRESS', time.strftime("%Y-%m-%d %H:%M:%S"), line)
line = re.sub(r'CURRENT_VERSION', svers, line)
print line, # preserve old content
if "<tbody>" in line:
print ("<tr>")
###PRINT MY STUFFS
print ("</tr>")
我为每个必须在html表中添加的表格行调用此函数。但是我要添加大约5k个表行(每行大约有30行hmtl代码)。它开始很快,但每行需要添加越来越多的时间。这是因为它必须为每一行重新编写文件吗?
有没有办法加快这个过程?
编辑感谢您的回复: 我喜欢创建我的大字符串的想法,只需要浏览一次文件。 我现在必须改变一些东西,因为我展示的功能是在Classe中。在我的主程序中,我只是迭代一个包含.json的文件夹。
for json in jsonfolder :
Object_a = CLASS-A(json) #unserialization
Object_a.write_to_html() (the function i showed)
我应该把它变成:
block_of_lines=''
for json in jsonfolder :
Object_a = CLASS-A(json) #unserialization
block_of_line += Object_a.to_html_sting()
Create_html(block_of_line)
那会更快吗?
答案 0 :(得分:1)
重读这个问题几次,出现以下想法。 你可以将写作分成3个块 - 一个用于标题,一个用于表格行,另一个用于页脚。它确实似乎取决于这三条替换线正在做什么,但如果我是对的,它们只能在第一次使用模板时更新线,即。在第一个json文件上执行操作,然后对其他文件保持不变。
file_footer = CLASS-A.write_html_header(path)
for json in jsonfolder :
Object_a = CLASS-A(json) #unserialization
Object_a.write_to_html(path) #use the part of the function
# that just handles the json file here
CLASS-A.write_html_footer(path, footer)
然后在你的类中,定义两个新的函数来将页眉和页脚编写为静态方法(这意味着它们可以从类而不是仅仅在实例上使用) 即(使用您自己代码中的副本)
@staticmethod
def write_html_header(path):
footer = []
save_for_later = false
for line in fileinput.input(path, inplace=1):
line = re.sub(r'CURRENT_APPLICATION', obj, line)
line = re.sub(r'IN_PROGRESS', time.strftime("%Y-%m-%d %H:%M:%S"), line)
line = re.sub(r'CURRENT_VERSION', svers, line)
# this blocks prints the header, and saves the
# footer from your template.
if save_for_later:
footer.append(line)
else:
print line, # preserve old content
if "<tbody>" in line:
save_for_later = true
return footer
我确实想知道你为什么编辑“inplace”并不意味着模板被覆盖,因此它不是一个模板而是一个单一的使用形式。通常,当我使用模板时,我从模板中读入,并将新模板写入模板的编辑版本。因此,模板可以一次又一次地重复使用。
对于页脚部分,以追加模式打开文件,然后在通过调用标题写入功能创建的页脚数组中写入行。
我认为不编辑模板对你有好处。那么你只需要:
open the template (read only)
open the new_file (in new, write mode)
write the header into new_file
loop over json files
append table content into new_file
append the footer into new_file
这样你就不会在循环json文件时重新读取你创建的文件的位。如果这是一个问题,你也不打算将整个文件存储在内存中。
答案 1 :(得分:-2)
5000行没什么。使用f.readlines()
读取整个文件以获取行列表:
with open(path) as f:
lines = f.readlines()
然后处理每一行,最后将它们连接到一个字符串并将整个事物写回文件。