views:

37

answers:

1

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
I need to save a picture, but a string, this is the problem I think. the text works here, just all about the images.
My tmp file always 0 kb
@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
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?
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