标签归档:temporary-directory

如何在Python中创建临时目录并获取路径/文件名

问题:如何在Python中创建临时目录并获取路径/文件名

如何在Python中创建临时目录并获取路径/文件名

how to create a temporary directory and get the path / file name in python


回答 0

使用模块中的mkdtemp()功能tempfile

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)

Use the mkdtemp() function from the tempfile module:

import tempfile
import shutil

dirpath = tempfile.mkdtemp()
# ... do stuff with dirpath
shutil.rmtree(dirpath)

回答 1

在Python 3,TemporaryDirectory临时文件可以使用的模块。

这直接来自示例

import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
     print('created temporary directory', tmpdirname)
# directory and contents have been removed

如果您想将目录保留更长的时间,则可以执行类似的操作(不是来自示例):

import tempfile
import shutil

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
shutil.rmtree(temp_dir.name)

正如@MatthiasRoelandts指出的那样,文档还指出“可以通过调用该cleanup()方法来显式清理目录”。

In Python 3, TemporaryDirectory in the tempfile module can be used.

This is straight from the examples:

import tempfile
with tempfile.TemporaryDirectory() as tmpdirname:
     print('created temporary directory', tmpdirname)
# directory and contents have been removed

If you would like to keep the directory a bit longer, then something like this could be done (not from the example):

import tempfile

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# use temp_dir, and when done:
temp_dir.cleanup()

The documentation also says that “On completion of the context or destruction of the temporary directory object the newly created temporary directory and all its contents are removed from the filesystem.” So at the end of the program, for example, Python will clean up the directory if it wasn’t explicitly removed. Python’s unittest may complain of ResourceWarning: Implicitly cleaning up <TemporaryDirectory... if you rely on this, though.


回答 2

为了扩展另一个答案,这是一个相当完整的示例,即使出现异常也可以清除tmpdir:

import contextlib
import os
import shutil
import tempfile

@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
        cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()
    def cleanup():
        shutil.rmtree(dirpath)
    with cd(dirpath, cleanup):
        yield dirpath

def main():
    with tempdir() as dirpath:
        pass # do something here

To expand on another answer, here is a fairly complete example which can cleanup the tmpdir even on exceptions:

import contextlib
import os
import shutil
import tempfile

@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)
        cleanup()

@contextlib.contextmanager
def tempdir():
    dirpath = tempfile.mkdtemp()
    def cleanup():
        shutil.rmtree(dirpath)
    with cd(dirpath, cleanup):
        yield dirpath

def main():
    with tempdir() as dirpath:
        pass # do something here

回答 3

在python 3.2及更高版本中,stdlib中有一个有用的contextmanager https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory

In python 3.2 and later, there is a useful contextmanager for this in the stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory


回答 4

如果我的问题正确无误,您还想知道临时目录中生成的文件名吗?如果是这样,请尝试以下操作:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

If I get your question correctly, you want to also know the names of the files generated inside the temporary directory? If so, try this:

import os
import tempfile

with tempfile.TemporaryDirectory() as tmp_dir:
    # generate some random files in it
     files_in_dir = os.listdir(tmp_dir)

在Python中获取临时目录的跨平台方法

问题:在Python中获取临时目录的跨平台方法

是否有跨平台的途径来获取 temp Python 2.6中目录?

例如,在Linux /tmp下为XP,而在XP下为C:\Documents and settings\[user]\Application settings\Temp

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.


回答 0

那将是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

为了完整起见,以下是根据文档搜索临时目录的方式:

  1. TMPDIR环境变量命名的目录。
  2. TEMP环境变量命名的目录。
  3. TMP环境变量命名的目录。
  4. 特定于平台的位置:
    • RiscOS上,由Wimp$ScrapDir环境变量。
    • 的Windows,目录C:\TEMPC:\TMP\TEMP,并\TMP按此顺序。
    • 在所有其他平台,目录/tmp/var/tmp以及/usr/tmp在这个顺序。
  5. 不得已时使用当前工作目录。

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.

回答 1

这应该做您想要的:

print tempfile.gettempdir()

对于我的Windows机器,我得到:

c:\temp

在我的Linux机器上,我得到:

/tmp

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

回答 2

我用:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

这是因为在MacOS,即达尔文,tempfile.gettempdir()os.getenv('TMPDIR')返回一个值,如'/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; 这是我并不总是想要的。

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.


回答 3

最简单的方法,基于@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这样的应用程序。他们只是使用较短的十六进制哈希值和特定于应用的前缀来“宣传”它们的存在。

The simplest way, based on @nosklo’s comment and answer:

import tempfile
tmp = tempfile.mkdtemp()

But if you want to manually control the creation of the directories:

import os
from tempfile import gettempdir
tmp = os.path.join(gettempdir(), '.{}'.format(hash(os.times())))
os.makedirs(tmp)

That way you can easily clean up after yourself when you are done (for privacy, resources, security, whatever) with:

from shutil import rmtree
rmtree(tmp, ignore_errors=True)

This is similar to what applications like Google Chrome and Linux systemd do. They just use a shorter hex hash and an app-specific prefix to “advertise” their presence.