What is the way to rename the following tempfile
pdf = render_me_some_pdf() #PDF RENDER
f = tempfile.NamedTemporaryFile()
f.write(pdf)
f.flush()
I read somethings about os.rename but I don't really now how to apply it
What is the way to rename the following tempfile
pdf = render_me_some_pdf() #PDF RENDER
f = tempfile.NamedTemporaryFile()
f.write(pdf)
f.flush()
I read somethings about os.rename but I don't really now how to apply it
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:
tempfile
object as a context manager, so we don't
need to worry about closing it explicitly.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')