Question

I am doing some processing with scripts and are currently using a fixed directory to do this file operations in. I want to use the tempfile module's tempdir to do this in a more elegant way.

using following code:

import os
import tempfile

#define the location of 'mytemp' parent folder relative to the system temp
sysTemp = tempfile.gettempdir()
myTemp = os.path.join(sysTemp,'mytemp')

#You must make sure myTemp exists
if not os.path.exists(myTemp):
    os.makedirs(myTemp)

on my mac it creates a folder in: /var/folders/nn/zyl78zb..... on pc it creates a (hidden folder inside my user directory.

From tempfile module documentation I understand that if you create a tempdir you have to clear it yourself. Sometimes I do want to go and look at intermediary files so I do not want to automatically delete them. If I leave them will the os eventually clean these directories (after reboot, etc)? If I do not clean them directly from script, following runs could likely get a different tempdir. This could eventually lead to large amount of unused and unwanted files.

I have scoured the tempfile documentation, but cannot seem to find an answer. It is probably more a OS question, but someone with tempfile module experience should know.

Was it helpful?

Solution

For example on linux often the /tmp is cleared on boot. But remember that many servers might be running continuously for years, so better not count on reboots. And on Windows then, temps are cleared whenever the disk cleanup is run, if never. Your program is responsible for deleting its tempfiles when it exists; the best way is to unlink them right after opening (on Unixen); use the best mechanism available in the tempfile module for whatever you do.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top