반응형
파이썬에서 임시 디렉토리를 만들고 경로 / 파일 이름을 얻는 방법
파이썬에서 임시 디렉토리를 만들고 경로 / 파일 이름을 얻는 방법
모듈 의 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)
반응형
'IT박스' 카테고리의 다른 글
malloc / free / new / delete에서 OS가 언제 그리고 왜 메모리를 0xCD, 0xDD 등으로 초기화합니까? (0) | 2020.07.15 |
---|---|
자바에서 숫자를 단어로 변환하는 방법 (0) | 2020.07.15 |
오류 : 인수가 함수가 아니며 정의되지 않았습니다. (0) | 2020.07.15 |
라이브러리를 사용하지 않고 querySelectorAll을 사용할 수없는 경우 속성별로 요소를 가져 오십니까? (0) | 2020.07.15 |
Eclipse Juno에 Marketplace 플러그인 설치 (0) | 2020.07.15 |