Replace a line in file using wildcard in Python
<p>So hopefully I havent overlooked the correct answer, but...
In keeping with the foo bar theme.
If I have a file that looks like this:</p>

<pre><code>blah boo who
bar blah blah
bar blah blah
foo some other chars
bar blah
black sheep
</code></pre>

<p>I want to be able to <strong>replace the line that starts with or includes <code>'foo'</code></strong> and replace the whole line with out knowing the following stuff.</p>

<p>My current code is nasty but works, is there a way to do it without loading the file and in a loop? or at least more efficiantly than this?</p>

<pre><code>filein = open("file", "r")
fileout = open("file.tmp", "w")
for line in filein:
    if line.startswith("foo"):
        fileout.write( "foo"+"my new numbers")
    else:
        fileout.write( line.replace('', '') )
filein.close()
fileout.close()
os.rename("file.tmp", "file")
</code></pre>
