Is it safe to open a file, write to it and NOT close it?
<p>I have quite a large Python(3) script that I'm trying to optimize.<br />
To my understanding when you use <code>with open(..., ...) as x</code> you <strong>DON'T</strong> need to use <code>.close()</code> at the end of the "with" block (it is automatically closed).<br /></p>

<p>I also know that you <strong>SHOULD</strong> add <code>.close()</code> (if you are not using <code>with</code>) after you are done manipulating the file, like this:</p>

<pre><code>f = open(..., ...)
f.write()
f.close()
</code></pre>

<p>In an attempt to shove 3 lines (above) into 1 line I tried to change this:</p>

<pre><code>with open(location, mode) as packageFile:
    packageFile.write()
</code></pre>

<p>Into this:</p>

<pre><code>open(location, mode).write(content).close()
</code></pre>

<p>Unfortunately this did not work and I got this error:</p>

<pre><code>Traceback (most recent call last):
  File "test.py", line 20, in &lt;module&gt;
    one.save("one.txt", sample)
  File "/home/nwp/Desktop/Python/test/src/one.py", line 303, in save
    open(location, mode).write(content).close()
AttributeError: 'int' object has no attribute 'close'
</code></pre>

<p>The same line works fine when I remove the <em><code>.close()</code></em> like this:</p>

<pre><code>open(location, mode).write(content)
</code></pre>

<p>Why didn't <code>open(location, mode).write(content).close()</code> work and is it safe to omit the <code>.close()</code> function?</p>