Rename python tempfile

The best way is copying the file and letting python delete the temporary one when it's closed:

I actually think you would be better off using os.link:

with tempfile.NamedTemporaryFile(dir=os.path.dirname(actual_name)) as f:
  f.write(pdf)
  os.link(f.name, actual_name)

This uses os.link to create a hard link to the temporary file, which will persist after the temporary file is automatically deleted.

This code has several advantages:

  • We're using the tempfile object as a context manager, so we don't need to worry about closing it explicitly.
  • Since we're creating a hardlink to the file, rather than copying it, we don't need to worry about disk space or time consumption due to copying a large file.
  • Since we're not copying the data, we don't need to call f.flush(). The file will be flushed automatically when it's closed.

You can access the filename via f.name. However, unless you use delete=False python will (try to) delete the temporary file automatically as soon as it is closed. Disabling auto deletion will keep the tempfile even if you do not save it - so that's not such a good idea.

The best way is copying the file and letting python delete the temporary one when it's closed:

import shutil
shutil.copy(f.name, 'new-name')

Tags:

Python