python-2.7 python用法 - Python 2.7中的tempfile.TemporaryDirectory上下文管理器



python意思 tempfile用法 (3)

有沒有辦法在Python 2.7的上下文管理器中創建臨時目錄?

with tempfile.TemporaryDirectory() as temp_dir:
    # modify files in this dir

# here the temporary diretory does not exist any more.

Answers

tempfile.TemporaryDirectory()已添加到Python 3.2中的tempfile標準庫中

它是tempfile.mkdtemp的簡單包裝器。 它以純Python編碼,可以輕鬆移植到Python 2.7。

例如:

from __future__ import print_function

import warnings as _warnings
import os as _os

from tempfile import mkdtemp

class TemporaryDirectory(object):
    """Create and return a temporary directory.  This has the same
    behavior as mkdtemp but can be used as a context manager.  For
    example:

        with TemporaryDirectory() as tmpdir:
            ...

    Upon exiting the context, the directory and everything contained
    in it are removed.
    """

    def __init__(self, suffix="", prefix="tmp", dir=None):
        self._closed = False
        self.name = None # Handle mkdtemp raising an exception
        self.name = mkdtemp(suffix, prefix, dir)

    def __repr__(self):
        return "<{} {!r}>".format(self.__class__.__name__, self.name)

    def __enter__(self):
        return self.name

    def cleanup(self, _warn=False):
        if self.name and not self._closed:
            try:
                self._rmtree(self.name)
            except (TypeError, AttributeError) as ex:
                # Issue #10188: Emit a warning on stderr
                # if the directory could not be cleaned
                # up due to missing globals
                if "None" not in str(ex):
                    raise
                print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
                      file=_sys.stderr)
                return
            self._closed = True
            if _warn:
                self._warn("Implicitly cleaning up {!r}".format(self),
                           ResourceWarning)

    def __exit__(self, exc, value, tb):
        self.cleanup()

    def __del__(self):
        # Issue a ResourceWarning if implicit cleanup needed
        self.cleanup(_warn=True)

    # XXX (ncoghlan): The following code attempts to make
    # this class tolerant of the module nulling out process
    # that happens during CPython interpreter shutdown
    # Alas, it doesn't actually manage it. See issue #10188
    _listdir = staticmethod(_os.listdir)
    _path_join = staticmethod(_os.path.join)
    _isdir = staticmethod(_os.path.isdir)
    _islink = staticmethod(_os.path.islink)
    _remove = staticmethod(_os.remove)
    _rmdir = staticmethod(_os.rmdir)
    _warn = _warnings.warn

    def _rmtree(self, path):
        # Essentially a stripped down version of shutil.rmtree.  We can't
        # use globals because they may be None'ed out at shutdown.
        for name in self._listdir(path):
            fullname = self._path_join(path, name)
            try:
                isdir = self._isdir(fullname) and not self._islink(fullname)
            except OSError:
                isdir = False
            if isdir:
                self._rmtree(fullname)
            else:
                try:
                    self._remove(fullname)
                except OSError:
                    pass
        try:
            self._rmdir(path)
        except OSError:
            pass

import os
with TemporaryDirectory() as tmp_dir:
    print("Temporary directory path: %s" % tmp_dir)
    print(os.path.isdir(tmp_dir))

# here the temporary diretory does not exist any more.
print(os.path.isdir(tmp_dir))

另一個選項是pypi上的“backports.tempfile”包: https://pypi.python.org/pypi/backports.tempfile ://pypi.python.org/pypi/backports.tempfile

引用項目的描述:“這個包提供了在backports命名空間下Python的tempfile模塊中的新功能的後端。”

安裝時間:

pip install backports.tempfile

然後在你的腳本中使用它:

from backports import tempfile
with tempfile.TemporaryDirectory() as temp_dir:
    # modify files in this dir
# here the temporary directory does not exist any more.

extend()可以與迭代器參數一起使用。 這是一個例子。 您希望以這種方式從列表列表中列出一個列表:

list2d = [[1,2,3],[4,5,6], [7], [8,9]]

你要

>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]

您可以使用itertools.chain.from_iterable()來執行此操作。 此方法的輸出是迭代器。 它的實現相當於

def from_iterable(iterables):
    # chain.from_iterable(['ABC', 'DEF']) --> A B C D E F
    for it in iterables:
        for element in it:
            yield element

回到我們的例子,我們可以做到

import itertools
list2d = [[1,2,3],[4,5,6], [7], [8,9]]
merged = list(itertools.chain.from_iterable(list2d))

並獲得通緝名單。

以下是如何extend()與iterator參數一起使用:

merged = []
merged.extend(itertools.chain.from_iterable(list2d))
print(merged)
>>>
[1, 2, 3, 4, 5, 6, 7, 8, 9]




python python-2.7 with-statement temp