How to generate temporary file in django and then destroy
You should use something from the tempfile
module. I think that it has everything you need.
I would add that Django has a built-in NamedTemporaryFile functionality in django.core.files.temp which is recommended for Windows users over using the tempfile module. This is because the Django version utilizes the O_TEMPORARY flag in Windows which prevents the file from being re-opened without the same flag being provided as explained in the code base here.
Using this would look something like:
from django.core.files.temp import NamedTemporaryFile
temp_file = NamedTemporaryFile(delete=True)
Here is a nice little tutorial about it and working with in-memory files, credit to Mayank Jain.
Python has the tempfile module for exactly this purpose. You do not need to worry about the location/deletion of the file, it works on all supported platforms.
There are three types of temporary files:
tempfile.TemporaryFile
- just basic temporary file,tempfile.NamedTemporaryFile
- "This function operates exactly asTemporaryFile()
does, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the name attribute of the file object.",tempfile.SpooledTemporaryFile
- "This function operates exactly asTemporaryFile()
does, except that data is spooled in memory until the file size exceedsmax_size
, or until the file’sfileno()
method is called, at which point the contents are written to disk and operation proceeds as withTemporaryFile()
.",
EDIT: The example usage you asked for could look like this:
>>> with TemporaryFile() as f:
f.write('abcdefg')
f.seek(0) # go back to the beginning of the file
print(f.read())
abcdefg