Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does python tempfile writes its files?

In python you can create a tempfile as follows:

tempfile.TemporaryFile()

And then you can write to it. Where is the file written in a GNU/Linux system? I can't seem to find it in the /tmp directory or any other directory.

Thank you,

like image 705
Loic Duros Avatar asked Aug 16 '13 18:08

Loic Duros


2 Answers

Call the tempfile.gettempdir() function:

Return the directory currently selected to create temporary files in.

You can change where temporary files are created by setting the tempfile.tempdir value to different directory if you want to influence where temporary files are created. Quoting from the documentation, if that value is None the rules are as follows:

If tempdir is unset or None at any call to any of the above functions, Python searches a standard list of directories and sets tempdir to the first one which the calling user can create files in. The list is:

  1. The directory named by the TMPDIR environment variable.
  2. The directory named by the TEMP environment variable.
  3. The directory named by the TMP environment variable.
  4. A platform-specific location:
    • On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
    • On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
    • On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
  5. As a last resort, the current working directory.
like image 108
Martijn Pieters Avatar answered Oct 25 '22 14:10

Martijn Pieters


Looking at .name on a file handle is indeed one way to see where the file exists. In the case of TemporaryFile (on *NIX systems), you'll see <fdopen>, indicating an open file handle, but no corresponding directory entry. You'll need to use NamedTemporaryFile if you'd like to preserve the link to the underlying file.


If you wish to control where temporary files go, look at the dir parameter:

TemporaryFile uses mkstemp, which allows setting the directory with the dir parameter:

If dir is specified, the file will be created in that directory; otherwise, a default directory is used. The default directory is chosen from a platform-dependent list, but the user of the application can control the directory location by setting the TMPDIR, TEMP or TMP environment variables.

like image 30
David Cain Avatar answered Oct 25 '22 16:10

David Cain