반응형
파일 출력이 있는 디렉토리 자동 생성
파일을 만들고 싶다:
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) 모두요?
Python 3.2+에서는 OP가 요구하는 API를 사용하여 다음 작업을 우아하게 수행할 수 있습니다.
import os
filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
Pathlib 모듈(Python 3.4에서 도입)에는 대체 구문이 있습니다(David258 감사합니다).
from pathlib import Path
output_file = Path("/foo/bar/baz.txt")
output_file.parent.mkdir(exist_ok=True, parents=True)
output_file.write_text("FOOBAR")
오래된 비단뱀에는 덜 우아한 방법이 있다.
함수는 이렇게 합니다.다음을 시도해 보십시오.
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
block은 디렉토리가 생성된 경우를 처리하는 것입니다.os.path.exists
및 그os.makedirs
인종적 조건으로부터 우리를 보호하려고 전화했어
언급URL : https://stackoverflow.com/questions/12517451/automatically-creating-directories-with-file-output
반응형
'programing' 카테고리의 다른 글
facebook graph api를 사용하여 사용자 프로필 사진을 표시하려면 어떻게 해야 하나요? (0) | 2022.10.15 |
---|---|
JavaScript로 쿠키 설정 및 쿠키 가져오기 (0) | 2022.10.15 |
컨텐츠 스크립트를 사용하여 페이지 컨텍스트 변수 및 함수에 액세스합니다. (0) | 2022.10.14 |
JSF backing bean 메서드에서 JSF 컴포넌트를 갱신할 수 있습니까? (0) | 2022.10.14 |
$_REQUEST, $_GET, $_POST 중 어느 것이 가장 빠릅니까? (0) | 2022.10.14 |