Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross-platform way of getting temp directory in Python

Is there a cross-platform way of getting the path to the temp directory in Python 2.6?

For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp.

like image 741
Joril Avatar asked May 11 '09 12:05

Joril


People also ask

How do I find the temp folder in Python?

This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp. This directory is used as default value of dir parameter.

How do I create a temp folder?

Open your File Explorer (it's usually the first button on your desktop taskbar, looks like a folder). Go to the "This PC" section on the left, and then double-click your C: drive. On the Home tab at the top, click "New Folder" and name it "Temp".


2 Answers

That would be the tempfile module.

It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.

Example:

import tempfile  print tempfile.gettempdir() # prints the current temporary directory  f = tempfile.TemporaryFile() f.write('something on temporaryfile') f.seek(0) # return to beginning of file print f.read() # reads data back from the file f.close() # temporary file is automatically deleted here 

For completeness, here's how it searches for the temporary directory, according to the documentation:

  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 111
nosklo Avatar answered Oct 06 '22 08:10

nosklo


This should do what you want:

print tempfile.gettempdir() 

For me on my Windows box, I get:

c:\temp 

and on my Linux box I get:

/tmp 
like image 27
RichieHindle Avatar answered Oct 06 '22 07:10

RichieHindle