temp
Python 2.6 でディレクトリ へのパスを取得するクロスプラットフォームの方法はありますか?
たとえば、Linux では 、/tmp
XP ではC:\Documents and settings\[user]\Application settings\Temp
.
temp
Python 2.6 でディレクトリ へのパスを取得するクロスプラットフォームの方法はありますか?
たとえば、Linux では 、/tmp
XP ではC:\Documents and settings\[user]\Application settings\Temp
.
それはtempfileモジュールです。
一時ディレクトリを取得する関数があり、名前付きまたは名前なしの一時ファイルとディレクトリを作成するためのショートカットもいくつかあります。
例:
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
完全を期すために、ドキュメントによると、一時ディレクトリを検索する方法は次のとおりです。
TMPDIR
環境変数によって指定されたディレクトリ。TEMP
環境変数によって指定されたディレクトリ。TMP
環境変数によって指定されたディレクトリ。Wimp$ScrapDir
、環境変数によって指定されたディレクトリ。C:\TEMP
、C:\TMP
、\TEMP
、およびがこの\TMP
順序で。/tmp
、/var/tmp
、および/usr/tmp
がこの順序で。これはあなたが望むことをするはずです:
print tempfile.gettempdir()
私のWindowsボックスでは、次のようになります。
c:\temp
私のLinuxボックスでは、次のようになります。
/tmp
@noskloのコメントと回答に基づく最も簡単な方法:
import tempfile
tmp = tempfile.mkdtemp()
しかし、ディレクトリの作成を手動で制御したい場合:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
そうすれば、(プライバシー、リソース、セキュリティなどのために) 作業が終わったら、次の方法で簡単にクリーンアップできます。
from shutil import rmtree
rmtree(tmp, ignore_errors=True)
これは、Google Chrome や Linux などのアプリケーションが行うことと似ていますsystemd
。より短い 16 進ハッシュとアプリ固有のプレフィックスを使用して、その存在を「アドバタイズ」します。