I am using tempfile.TemporaryFile
for some intermediate processing. The program nicely removes the temp file for me when it closes, which is precisely the behaviour that I want the majority of the time. But is there a way to save the file for examination in the event of a (trapped) error or other abnormal circumstance?
Asked
Active
Viewed 7,588 times
8

djvg
- 11,722
- 5
- 72
- 103

TimothyAWiseman
- 14,385
- 12
- 40
- 47
-
related: https://stackoverflow.com/q/94153 – djvg Feb 07 '22 at 17:00
2 Answers
8
Seek to the beginning and use shutil.copyfileobj()
to copy the data to a file you create.

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
3
Use tempfile.mkstemp()
. According to the documentation:
Unlike TemporaryFile(), the user of mkstemp() is responsible for deleting the temporary file when done with it.
Read more here.

dhg
- 52,383
- 8
- 123
- 144
-
1"which is precisely the behaviour that I want the majority of the time" – Ignacio Vazquez-Abrams Apr 12 '12 at 17:19
-
Thanks. It looks like this would work, but it seems to add a lot more complexity compared with shutil.copyfileobj() – TimothyAWiseman Apr 12 '12 at 17:47