write into file without reading all the file
<p>I have a template of a file (html) with the header and footer. I try to insert text into right after <code>&lt;trbody&gt;</code>.
The way i'm doing it right now is with <code>fileinput.input()</code> </p>

<pre><code>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 "&lt;tbody&gt;" in line:
        print ("&lt;tr&gt;")  
        ###PRINT MY STUFFS
        print ("&lt;/tr&gt;")
</code></pre>

<p>I call this for each Table-line I have to add in my html table. but I have around 5k table-lines to add (each line is about 30 lines of hmtl code). It starts fast, but each line takes more and more times to be added. It's because it has to write the file all over again for each line right ?</p>

<p>Is there a way to speed up the process?</p>

<p>EDIT thanks for the responses :
I like the idee of creating my big string, and the just go through the file just once.
I'll have to change some stuff because right now because the function I showed is in a Classe. and in my main programe, I just iterate on a folder containing .json.</p>

<pre><code> for json in jsonfolder :
     Object_a = CLASS-A(json) #unserialization
     Object_a.write_to_html()   (the function i showed)
</code></pre>

<p>I should turn that into :</p>

<pre><code>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)
</code></pre>

<p>Would that be faster ?</p>

<p>5000 lines is nothing. Read the entire file using <code>f.readlines()</code> to get a list of lines:</p>

<pre><code>with open(path) as f:
    lines = f.readlines()
</code></pre>

<p>Then process each line, and eventually join them to one string and write the entire thing back to the file.</p>

python python-2.7