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
To rename files in Python, use the rename() method of the os module. The parameters of the rename() method are the source address (old name) and the destination address (new name).
Creating a named Temporary FilesThe NamedTemporaryFile() function creates a file with a name, accessed from the name attribute. First import tempfile and then the file is created using the NamedTemporaryFile() function.
# importing the os module import os # Source src = 'filee. text' # Destination dest = 'file. txt' # Renaming the file os. rename(src, dest) print ("The file has been renamed.")
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With