Hey I need to save a temporarily jpg file and then remove it, is there any better way to do? I tested the tempfile, but looks that doesn't work.
+1
A:
tempfile
does work. What did you try?
>>> with tempfile.NamedTemporaryFile(mode="wb") as jpg:
... jpg.write(b"Hello World!")
... print jpg.name
...
c:\users\<...>\appdata\local\temp\tmpv7hy__
jpg
will be closed as soon as the with
block is left. If you pass in the optional argument delete
, it will be deleted on close.
katrielalex
2010-10-26 16:31:56
I need to save a picture, but a string, this is the problem I think. the text works here, just all about the images.
2010-10-26 16:33:29
My tmp file always 0 kb
2010-10-26 16:34:28
@user: I don't really understand what you mean. In what format do you have the picture -- a sequence of bytes? Some string encoding of a `jpg`? Posting some code might help.
katrielalex
2010-10-26 16:48:39
For example, what I need is create a tmpfile, and send the path to another function as input, and that function write something onto this file, and then return the object, after this has done, the file gets removed. Is there possible to do this?
2010-10-27 02:38:06
Yes, that's fine. It should be fairly clear how to do that from the code above: pass `jpg`, the temporary file, to the second function. That function can then write whatever it wants to `jpg`; once it's done, you can `del jpg` and the file will be automatically cleaned up by the OS.
katrielalex
2010-10-27 15:19:20