Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename python tempfile

Tags:

python

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

like image 814
nelsonvarela Avatar asked May 11 '12 08:05

nelsonvarela


People also ask

How do you rename a file in Python?

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).

How do you name a temp file in Python?

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.

How do I rename an existing file with an os module in Python?

# 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.")


2 Answers

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.
like image 61
larsks Avatar answered Dec 22 '22 18:12

larsks


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')
like image 24
ThiefMaster Avatar answered Dec 22 '22 17:12

ThiefMaster