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?
The directory named by the TEMP environment variable. The directory named by the TMP environment variable. A platform-specific location: On Windows, the directories C:\TEMP , C:\TMP , \TEMP , and \TMP , in that order.
If you want to write text data into a temp file, you can use the writelines() method instead. For using this method, we need to create the tempfile using w+t mode instead of the default w+b mode. To do this, a mode param can be passed to TemporaryFile() to change the mode of the created temp file.
import tempfile # create a temporary directory using the context manager with tempfile. TemporaryDirectory() as tmpdirname: print('created temporary directory', tmpdirname) # Outside the context manager, directory and contents have been removed.
Seek to the beginning and use shutil.copyfileobj()
to copy the data to a file you create.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With