import tempfile
import shutil
...
f_old = open(input_file, 'r')
with tempfile.NamedTemporaryFile() as tmp:
for line in f_old:
tmp.write(line.replace(old_string, new_string))
f_old.close()
tmp.flush()
os.fsync(tmp)
shutil.copy2(tmp.name, input_file)
tmp.close()