Jor*_*ril 227 python cross-platform temporary-directory
是否有跨平台的方式获取tempPython 2.6中的目录路径?
例如,在Linux /tmp下,在XP下C:\Documents and settings\[user]\Application settings\Temp.
nos*_*klo 339
那将是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
Run Code Online (Sandbox Code Playgroud)
为了完整起见,根据文档,它是如何搜索临时目录的:
TMPDIR环境变量命名的目录.TEMP环境变量命名的目录.TMP环境变量命名的目录.Wimp$ScrapDir环境变量命名的目录.C:\TEMP,C:\TMP,\TEMP,并\TMP按此顺序./tmp,/var/tmp以及/usr/tmp在这个顺序.Ric*_*dle 57
这应该做你想要的:
print tempfile.gettempdir()
Run Code Online (Sandbox Code Playgroud)
在我的Windows机箱上,我得到:
c:\temp
Run Code Online (Sandbox Code Playgroud)
在我的Linux机器上,我得到:
/tmp
Run Code Online (Sandbox Code Playgroud)
Acu*_*nus 11
我用:
import platform
import tempfile
tempdir = '/tmp' if platform.system() == 'Darwin' else tempfile.gettempdir()
Run Code Online (Sandbox Code Playgroud)
这是因为在MacOS上,即达尔文,tempfile.gettempdir()并os.getenv('TMPDIR')返回如此值'/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; 这是我不想要的!
hob*_*obs 10
从@nosklo的答案中取出重要的一点并添加一个半私人沙箱目录:
import tempfile
tmp = tempfile.mkdtemp()
Run Code Online (Sandbox Code Playgroud)
这样,当您完成后(隐私,资源,安全等),您可以轻松地清理自己:
import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)
Run Code Online (Sandbox Code Playgroud)
这类似于Google Chrome和Linux等应用程序systemd.他们只是使用较短的十六进制哈希和特定于应用程序的前缀来"宣传"他们的存在.
| 归档时间: |
|
| 查看次数: |
93459 次 |
| 最近记录: |