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.
Asked
Active
Viewed 1.6k times
4
-
4what have you tested? where is your code? what doesn't work? – SilentGhost Oct 26 '10 at 16:31
1 Answers
7
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.

Katriel
- 120,462
- 19
- 136
- 170
-
1I need to save a picture, but a string, this is the problem I think. the text works here, just all about the images. – user469652 Oct 26 '10 at 16:33
-
1@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. – Katriel Oct 26 '10 at 16:48
-
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? – user469652 Oct 27 '10 at 02:38
-
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. – Katriel Oct 27 '10 at 15:19
-
1FYI: NamedTemporaryFile takes file suffix as an argument. https://stackoverflow.com/a/38900260 – yang5 Dec 01 '18 at 21:26