IT박스

파이썬에서 임시 디렉토리를 만들고 경로 / 파일 이름을 얻는 방법

itboxs 2020. 7. 15. 07:53
반응형

파이썬에서 임시 디렉토리를 만들고 경로 / 파일 이름을 얻는 방법


파이썬에서 임시 디렉토리를 만들고 경로 / 파일 이름을 얻는 방법


모듈 mkdtemp()기능을 사용하십시오 tempfile.

import tempfile
import shutil

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

다른 답변을 확장하기 위해 예외 상황에서도 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

python 3.2 이상에서는 stdlib https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory 에 유용한 컨텍스트 관리자가 있습니다.


Python 3에서는 tempfile 모듈의 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)

참고URL : https://stackoverflow.com/questions/3223604/how-to-create-a-temporary-directory-and-get-the-path-file-name-in-python

반응형