title: In python, make a tempfile in the same directory as another file?
body: <p>I need to update a file.  I read it in and write it out with changes. However, I'd prefer to write to a temporary file and rename it into place.</p>
  <pre><code>temp = tempfile.NamedTemporaryFile()
  tempname = temp.name
  temp.write(new_data)
  temp.close()
  os.rename(tempname, data_file_name)
  </code></pre>
  <p>The problem is that <code>tempfile.NamedTemporaryFile()</code> makes the temporary file in <code>/tmp</code> which is a different file system.  This means <code>os.rename()</code> fails.  If I use <code>shlib.move()</code> instead then I don't have the atomic update that <code>mv</code> provides (for files in the same file system, yadda, yadda, etc.)</p>
  <p>I know <code>tempfile.NamedTemporaryFile()</code> takes a <code>dir</code> parameter, but <code>data_file_name</code> might be <code>&quot;foo.txt&quot;</code> in which case <code>dir='.'</code>; or <code>data_file_name</code> might be <code>&quot;/path/to/the/data/foo.txt&quot;</code> in which case <code>dir=&quot;/path/to/the/data&quot;</code>.</p>
  <p>What I'd really like is the temp file to be <code>data_file_name + &quot;some random data&quot;</code>. This would have the benefit of failing in a way that would leave behind useful clues.</p>
  <p>Suggestions?</p>