Write to a file with sudo privileges in Python : <p>The following code throws an error if it's run by a non-root user for a file owned by root, even when the non-root user has sudo privileges:</p>

<pre><code>try:
  f = open(filename, "w+")
except IOError:
  sys.stderr.write('Error: Failed to open file %s' % (filename))
f.write(response + "\n" + new_line)
f.close()
</code></pre>

<p>Is there a way to run <code>open(filename, "w+")</code> with sudo privileges, or an alternative function that does this?</p>
