tempfile.TemporaryDirectory context manager in Python 2.7

前端 未结 2 1180
醉梦人生
醉梦人生 2020-12-15 15:27

Is there a way to create a temporary directory in a context manager with Python 2.7?

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


        
2条回答
  •  粉色の甜心
    2020-12-15 15:48

    Another option is the "backports.tempfile" package on pypi: https://pypi.python.org/pypi/backports.tempfile

    Quoting the project's description: "This package provides backports of new features in Python’s tempfile module under the backports namespace."

    Install with:

    pip install backports.tempfile
    

    Then use it in your script:

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

提交回复
热议问题