development

파일 출력으로 디렉토리 자동 생성

big-blog 2020. 3. 17. 23:36
반응형

파일 출력으로 디렉토리 자동 생성


가능한 중복 :
파이썬에서 mkdir -p 기능

파일을 만들고 싶다고 가정 해보십시오.

filename = "/foo/bar/baz.txt"

with open(filename, "w") as f:
    f.write("FOOBAR")

존재하지 않기 IOError때문에 이것은을 제공 /foo/bar합니다.

해당 디렉토리를 자동으로 생성하는 가장 파이썬적인 방법은 무엇입니까? 명시 적으로 호출 os.path.exists하고 os.mkdir모든 단일 항목 (예 : / foo, 그런 다음 / foo / bar)이 필요합니까?


os.makedirs기능은이 작업을 수행합니다. 다음을 시도하십시오 :

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

try-except블록 을 추가하는 이유 는 디렉토리가 호출 os.path.existsos.makedirs호출 사이에 작성된 경우를 처리하여 경쟁 조건으로부터 우리를 보호하기 위해서입니다.


Python 3.2 이상에서는 위의 경쟁 조건을 피하는 보다 우아한 방법 이 있습니다.

filename = "/foo/bar/baz.txt"¨
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

참고 URL : https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output


반응형