질문자 :Parand
파일이 기록될 디렉토리가 있는지 확인하는 가장 우아한 방법은 무엇이며, 없으면 Python을 사용하여 디렉토리를 생성합니까? 내가 시도한 것은 다음과 같습니다.
import os file_path = "/my/directory/filename.txt" directory = os.path.dirname(file_path) try: os.stat(directory) except: os.mkdir(directory) f = file(filename)
여하튼, 나는 os.path.exists
놓쳤습니다(kanja, Blair 및 Douglas에게 감사드립니다). 이것이 내가 가진 것입니다.
def ensure_dir(file_path): directory = os.path.dirname(file_path) if not os.path.exists(directory): os.makedirs(directory)
이 작업을 자동으로 수행하는 "열기" 플래그가 있습니까?
Python ≥ 3.5에서는 pathlib.Path.mkdir
사용합니다.
from pathlib import Path Path("/my/directory").mkdir(parents=True, exist_ok=True)
이전 버전의 Python의 경우 각각 작은 결함이 있는 좋은 품질의 두 가지 답변이 있으므로 이에 대한 답변을 드리겠습니다.
os.path.exists
시도하고 생성을 위해 os.makedirs
를 고려하십시오.
import os if not os.path.exists(directory): os.makedirs(directory)
주석 및 다른 곳에서 언급했듯이 경쟁 조건이 있습니다. os.path.exists
와 os.makedirs
호출 os.makedirs
OSError
와 함께 실패합니다. OSError
포괄적으로 포착하고 계속하는 것은 권한 부족, 디스크 가득 참 등과 같은 다른 요인으로 인한 디렉토리 생성 실패를 무시하기 때문에 완벽하지 않습니다.
한 가지 옵션은 OSError
를 트래핑하고 포함된 오류 코드를 검사하는 것입니다(Python의 OSError에서 정보를 가져오는 플랫폼 간 방법 참조).
import os, errno try: os.makedirs(directory) except OSError as e: if e.errno != errno.EEXIST: raise
또는 두 번째 os.path.exists
가 있을 수 있지만 첫 번째 확인 후에 다른 사람이 디렉터리를 생성한 다음 두 번째 확인 전에 디렉터리를 제거했다고 가정합니다. 여전히 속일 수 있습니다.
응용 프로그램에 따라 동시 작업의 위험은 파일 권한과 같은 다른 요인으로 인한 위험보다 많거나 적을 수 있습니다. 개발자는 구현을 선택하기 전에 개발 중인 특정 응용 프로그램과 예상 환경에 대해 더 많이 알아야 합니다.
FileExistsError
(3.3 이상에서)를 노출하여 이 코드를 상당히 개선합니다.
try: os.makedirs("path/to/directory") except FileExistsError: # directory already exists pass
... 그리고 허용하여 에 키워드 인수 os.makedirs
라는 exist_ok
(3.2 이상에서)를.
os.makedirs("path/to/directory", exist_ok=True) # succeeds even if directory exists.
Blair Conrad파이썬 3.5 이상:
import pathlib pathlib.Path('/my/directory').mkdir(parents=True, exist_ok=True)
pathlib.Path.mkdir
은 재귀적으로 디렉토리를 생성하고 디렉토리가 이미 존재하는 경우 예외를 발생시키지 않습니다. 부모가 필요하지 않거나 생성되기를 원하는 경우 parents
인수를 건너뜁니다.
파이썬 3.2 이상:
pathlib
사용:
당신이 설치할 수있는 경우 현재 pathlib
이름이 백 포트 pathlib2
. pathlib
라는 이전의 유지 관리되지 않는 백포트를 설치하지 마십시오. 다음으로, 위의 Python 3.5+ 섹션을 참조하고 동일하게 사용하십시오.
Python 3.4를 사용하는 경우 pathlib
exist_ok
옵션이 누락되었습니다. 백포트는 이 누락된 옵션을 포함 mkdir
의 새롭고 우수한 구현을 제공하기 위한 것입니다.
운영 os
사용:
import os os.makedirs(path, exist_ok=True)
os.makedirs
는 재귀적으로 디렉토리를 생성하고 디렉토리가 이미 존재하는 경우 예외를 발생시키지 않습니다. Python 3.2 이상을 사용하는 경우에만 선택적 exist_ok
False
입니다. 이 인수는 Python 2.x 2.7까지 존재하지 않습니다. 따라서 Python 2.7에서와 같이 수동 예외 처리가 필요하지 않습니다.
파이썬 2.7 이상:
pathlib
사용:
당신이 설치할 수있는 경우 현재 pathlib
이름이 백 포트 pathlib2
. pathlib
라는 이전의 유지 관리되지 않는 백포트를 설치하지 마십시오. 다음으로, 위의 Python 3.5+ 섹션을 참조하고 동일하게 사용하십시오.
운영 os
사용:
import os try: os.makedirs(path) except OSError: if not os.path.isdir(path): raise
순진한 솔루션은 먼저 os.path.isdir
다음에 os.makedirs
사용할 수 있지만 위의 솔루션은 두 작업의 순서를 반대로 합니다. 이렇게 하면 디렉터리를 만들려는 중복된 시도와 관련된 일반적인 경합 상태를 방지하고 디렉터리에서 파일을 명확하게 구분합니다.
errno
OSError: [Errno 17] File exists
, 즉 errno.EEXIST
가 파일과 디렉토리 모두에 대해 발생하기 때문에 유용성이 제한적이라는 점에 유의하십시오. 단순히 디렉토리가 존재하는지 확인하는 것이 더 안정적입니다.
대안:
mkpath
는 중첩된 디렉토리를 생성하고 디렉토리가 이미 존재하는 경우 아무 것도 하지 않습니다. 이것은 Python 2와 3 모두에서 작동합니다.
import distutils.dir_util distutils.dir_util.mkpath(path)
버그 10948 에 따라 이 대안의 심각한 제한은 주어진 경로에 대해 파이썬 프로세스당 한 번만 작동한다는 것입니다. 즉, 디렉토리를 생성하는 데 사용하고 Python 내부 또는 외부에서 디렉토리를 삭제한 다음 mkpath
다시 사용하여 동일한 디렉토리를 다시 생성하면 mkpath
는 단순히 이전에 디렉토리를 생성했다는 잘못된 캐시 정보를 자동으로 사용하고, 실제로 디렉토리를 다시 만들지 않습니다. 대조적으로 os.makedirs
는 그러한 캐시에 의존하지 않습니다. 이 제한은 일부 응용 프로그램에 적합할 수 있습니다.
디렉토리의 모드 와 관련하여 신경이 쓰이는 경우 문서를 참조하십시오.
Asclepiustry 예외를 사용하고 errno 모듈의 올바른 오류 코드는 경쟁 조건을 제거하고 플랫폼 간입니다.
import os import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
즉, 디렉토리를 생성하려고 시도하지만 디렉토리가 이미 존재하는 경우 오류를 무시합니다. 반면에 다른 모든 오류가 보고됩니다. 예를 들어 dir 'a'를 미리 만들고 모든 권한을 제거하면 errno.EACCES
(권한 거부됨, 오류 13)와 함께 OSError
Heikki Toivonenos.path.exists()
os.path.isdir()
을 사용하여 테스트하는 것이 좋습니다.
>>> os.path.exists('/tmp/dirname') True >>> os.path.exists('/tmp/dirname/filename.etc') True >>> os.path.isdir('/tmp/dirname/filename.etc') False >>> os.path.isdir('/tmp/fakedirname') False
당신이 가지고 있다면:
>>> dir = raw_input(":: ")
그리고 어리석은 사용자 입력:
:: /tmp/dirname/filename.etc
os.path.exists()
테스트하는 경우 해당 인수를 os.makedirs()
filename.etc
라는 디렉토리로 끝날 것입니다.
crimsonstonePython 3.5부터 pathlib.Path.mkdir
에는 exist_ok
플래그가 있습니다.
from pathlib import Path path = Path('/my/directory/filename.txt') path.parent.mkdir(parents=True, exist_ok=True) # path.parent ~ os.path.dirname(path)
이것은 재귀적으로 디렉토리를 생성하고 디렉토리가 이미 존재하는 경우 예외를 발생시키지 않습니다.
(마찬가지로os.makedirs
가지고 exist_ok
파이썬 3.2에서 시작 플래그를 예를 들어 os.makedirs(path, exist_ok=True)
)
참고: 내가 이 답변을 게시했을 때 언급된 다른 답변은 exist_ok
하지 않습니다_ok ...
hiro protagonistos.makedirs
확인: (전체 경로가 존재하는지 확인합니다.)
디렉토리가 존재할 수 있다는 사실을 처리하려면 OSError
잡으십시오. ( exist_ok
가 False
(기본값)이면 대상 디렉토리가 이미 존재하면 OSError
import os try: os.makedirs('./path/to/somewhere') except OSError: pass
Douglas Mayle이 상황의 세부 사항에 대한 통찰력
특정 경로에 특정 파일을 제공하고 파일 경로에서 디렉토리를 가져옵니다. 그런 다음 디렉토리가 있는지 확인한 후 읽기 위해 파일을 열려고 시도합니다. 이 코드에 댓글을 작성하려면:
filename = "/my/directory/filename.txt" dir = os.path.dirname(filename)
dir
덮어쓰는 것을 피하고 싶습니다. 또한 filepath
또는 fullfilepath
filename
보다 더 나은 의미 체계 이름이므로 다음과 같이 작성하는 것이 좋습니다.
import os filepath = '/my/directory/filename.txt' directory = os.path.dirname(filepath)
최종 목표는 처음에 언급한 이 파일을 작성하기 위해 여는 것이지만 본질적으로 다음과 같이 이 목표에 접근하고 있습니다(코드 기반). 그러면 읽기 위해 파일이 열립니다.
if not os.path.exists(directory): os.makedirs(directory) f = file(filename)
읽기를 위한 개방을 가정
거기에 있고 읽을 수 있을 것으로 예상되는 파일의 디렉토리를 만드는 이유는 무엇입니까?
파일을 열어보십시오.
with open(filepath) as my_file: do_stuff(my_file)
디렉토리나 파일이 없으면 관련 오류 번호와 함께 IOError
errno.ENOENT
는 플랫폼에 관계없이 올바른 오류 번호를 가리킵니다. 원하는 경우 잡을 수 있습니다. 예를 들면 다음과 같습니다.
import errno try: with open(filepath) as my_file: do_stuff(my_file) except IOError as error: if error.errno == errno.ENOENT: print 'ignoring error because directory or file is not there' else: raise
쓰기 시작한다고 가정하면
이것은 아마도 당신이 원하는 것입니다.
이 경우 경쟁 조건에 직면하지 않을 수 있습니다. 그러니 그냥 쓰기 위해, 당신은 함께 열 필요가 있다고 말하자면,하지만 노트 w
모드 (또는 추가 할). a
또한 파일을 여는 데 컨텍스트 관리자를 사용하는 것이 Python 모범 사례입니다.
import os if not os.path.exists(directory): os.makedirs(directory) with open(filepath, 'w') as my_file: do_stuff(my_file)
그러나 모든 데이터를 동일한 디렉토리에 넣으려는 여러 Python 프로세스가 있다고 가정해 보겠습니다. 그러면 디렉토리 생성에 대한 경합이 있을 수 있습니다. makedirs
호출을 try-except 블록으로 래핑하는 것이 가장 좋습니다.
import os import errno if not os.path.exists(directory): try: os.makedirs(directory) except OSError as error: if error.errno != errno.EEXIST: raise with open(filepath, 'w') as my_file: do_stuff(my_file)
Aaron Hallos.path.exists
기능을 사용해보십시오
if not os.path.exists(dir): os.mkdir(dir)
gone나는 다음을 내려놓았다. 그래도 완전히 안전한 것은 아닙니다.
import os dirname = 'create/me' try: os.makedirs(dirname) except OSError: if os.path.exists(dirname): # We are nearly safe pass else: # There was an error on creation, so make sure we know about it raise
이제 내가 말했듯이 이것은 디렉토리 생성에 실패할 가능성이 있고 그 기간 동안 디렉토리를 생성하는 또 다른 프로세스가 있기 때문에 이것은 정말 완벽한 방법이 아닙니다.
Ali Afshar디렉토리가 존재하는지 확인하고 필요한 경우 생성하시겠습니까?
이에 대한 직접적인 대답은 다른 사용자나 프로세스가 디렉터리를 엉망으로 만들 것으로 예상하지 않는 간단한 상황을 가정하는 것입니다.
if not os.path.exists(d): os.makedirs(d)
또는 디렉토리를 만드는 것이 경합 조건의 영향을 받는 경우(즉, 경로가 존재하는지 확인한 후 다른 것이 이미 만든 경우) 다음을 수행하십시오.
import errno try: os.makedirs(d) except OSError as exception: if exception.errno != errno.EEXIST: raise
tempfile
통해 임시 디렉토리를 사용하여 리소스 경합 문제를 피하는 것입니다.
import tempfile d = tempfile.mkdtemp()
온라인 문서의 필수 사항은 다음과 같습니다.
mkdtemp(suffix='', prefix='tmp', dir=None) User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. The directory is readable, writable, and searchable only by the creating user. Caller is responsible for deleting the directory when done with it.
Python 3.5의 새로운 기능: pathlib.Path
있는 exist_ok
Path
와 함께 사용하고 싶은 많은 메서드가 있는 새로운 Path 개체(3.4 기준)가 있습니다. mkdir
(상황에 따라 스크립트를 사용하여 주간 담당자를 추적하고 있습니다. 동일한 데이터에 대해 하루에 한 번 이상 스택 오버플로가 발생하지 않도록 하는 스크립트의 관련 코드 부분이 있습니다.)
먼저 관련 수입품:
from pathlib import Path import tempfile
os.path.join
을 처리할 필요가 없습니다. /
결합하기만 하면 됩니다.
directory = Path(tempfile.gettempdir()) / 'sodata'
exist_ok
디렉토리가 존재하는지 확인합니다. Existing_ok 인수가 Python 3.5에 표시됩니다.
directory.mkdir(exist_ok=True)
문서 의 관련 부분은 다음과 같습니다.
exist_ok
가 true이면 FileExistsError
예외는 무시 POSIX mkdir -p
명령과 동일한 동작), 마지막 경로 구성 요소가 기존의 비 디렉터리 파일이 아닌 경우에만 무시됩니다.
여기에 스크립트가 조금 더 있습니다. 제 경우에는 경쟁 조건의 대상이 아니며 디렉터리(또는 포함된 파일)가 있을 것으로 예상하는 프로세스가 하나만 있으며 제거하려는 것이 없습니다. 디렉토리.
todays_file = directory / str(datetime.datetime.utcnow().date()) if todays_file.exists(): logger.info("todays_file exists: " + str(todays_file)) df = pd.read_json(str(todays_file))
str
경로를 예상하는 다른 API가 이를 사용할 수 Path
str
로 강제 변환해야 합니다.
아마도 Pandas는 추상 기본 클래스인 os.PathLike
인스턴스를 허용하도록 업데이트되어야 합니다.
Aaron HallPython 3.4에서는 새로운 pathlib
모듈을 사용할 수도 있습니다.
from pathlib import Path path = Path("/my/directory/filename.txt") try: if not path.parent.exists(): path.parent.mkdir(parents=True) except OSError: # handle error; you can also catch specific errors like # FileExistsError and so on.
Antti Haapala한 줄짜리 솔루션의 경우 IPython.utils.path.ensure_dir_exists()
사용할 수 있습니다.
from IPython.utils.path import ensure_dir_exists ensure_dir_exists(dir)
문서에서 : 디렉토리가 존재하는지 확인하십시오. 존재하지 않는 경우 생성을 시도하고 다른 프로세스가 동일한 작업을 수행하는 경우 경쟁 조건으로부터 보호하십시오.
IPython은 표준 라이브러리의 일부가 아닌 확장 패키지입니다.
tashuhkaPython3 에서 os.makedirs
exist_ok
설정을 지원합니다. 기본 설정은 False
이며, 이는 대상 디렉토리가 이미 존재하는 경우 OSError
exist_ok
를 True
로 설정하면 OSError
(디렉터리 존재)가 무시되고 디렉터리가 생성되지 않습니다.
os.makedirs(path,exist_ok=True)
Python2 에서 os.makedirs
exist_ok
설정을 지원하지 않습니다. heikki-toivonen의 답변 에서 접근 방식을 사용할 수 있습니다.
import os import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise
euccas관련 Python 문서 는 EAFP 코딩 스타일(허가보다 용서를 구하는 것이 더 쉬움) 의 사용을 제안합니다. 이것은 코드가
try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise else: print "\nBE CAREFUL! Directory %s already exists." % path
대안보다 낫다
if not os.path.exists(path): os.makedirs(path) else: print "\nBE CAREFUL! Directory %s already exists." % path
문서는 이 질문에서 논의된 경쟁 조건 때문에 정확히 이것을 제안합니다. 또한 여기에서 다른 사람들이 언급한 것처럼 OS를 두 번 쿼리하는 대신 한 번 쿼리하면 성능상의 이점이 있습니다. 마지막으로 개발자가 응용 프로그램이 실행 중인 환경을 알고 있는 경우에 잠재적으로 두 번째 코드에 찬성하는 주장은 프로그램이 개인 환경을 설정한 특별한 경우에만 옹호될 수 있습니다. 자체(및 동일한 프로그램의 다른 인스턴스).
이 경우에도 이것은 나쁜 습관이며 오랫동안 쓸모없는 디버깅으로 이어질 수 있습니다. 예를 들어, 디렉토리에 대한 권한을 설정했다는 사실이 우리의 목적에 맞게 적절하게 설정된 노출 권한을 남겨두어서는 안 됩니다. 상위 디렉토리는 다른 권한으로 마운트될 수 있습니다. 일반적으로 프로그램은 항상 올바르게 작동해야 하며 프로그래머는 특정 환경을 기대해서는 안 됩니다.
kavadiasmkpath
를 사용할 수 있습니다.
# Create a directory and any missing ancestor directories. # If the directory already exists, do nothing. from distutils.dir_util import mkpath mkpath("test")
조상 디렉토리도 생성한다는 점에 유의하십시오.
Python 2 및 3에서 작동합니다.
Dennis Golomazov나는 이 Q/A를 찾았고 처음에는 내가 받고 있던 몇 가지 실패와 오류에 어리둥절했습니다. 저는 Python 3(Arch Linux x86_64 시스템의 Anaconda 가상 환경의 v.3.5)에서 작업하고 있습니다.
다음 디렉토리 구조를 고려하십시오.
└── output/ ## dir ├── corpus ## file ├── corpus2/ ## dir └── subdir/ ## dir
다음은 내 실험/노트입니다.
# ---------------------------------------------------------------------------- # [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist import pathlib """ Notes: 1. Include a trailing slash at the end of the directory path ("Method 1," below). 2. If a subdirectory in your intended path matches an existing file with same name, you will get the following error: "NotADirectoryError: [Errno 20] Not a directory:" ... """ # Uncomment and try each of these "out_dir" paths, singly: # ---------------------------------------------------------------------------- # METHOD 1: # Re-running does not overwrite existing directories and files; no errors. # out_dir = 'output/corpus3' ## no error but no dir created (missing tailing /) # out_dir = 'output/corpus3/' ## works # out_dir = 'output/corpus3/doc1' ## no error but no dir created (missing tailing /) # out_dir = 'output/corpus3/doc1/' ## works # out_dir = 'output/corpus3/doc1/doc.txt' ## no error but no file created (os.makedirs creates dir, not files! ;-) # out_dir = 'output/corpus2/tfidf/' ## fails with "Errno 20" (existing file named "corpus2") # out_dir = 'output/corpus3/tfidf/' ## works # out_dir = 'output/corpus3/a/b/c/d/' ## works # [2] https://docs.python.org/3/library/os.html#os.makedirs # Uncomment these to run "Method 1": #directory = os.path.dirname(out_dir) #os.makedirs(directory, mode=0o777, exist_ok=True) # ---------------------------------------------------------------------------- # METHOD 2: # Re-running does not overwrite existing directories and files; no errors. # out_dir = 'output/corpus3' ## works # out_dir = 'output/corpus3/' ## works # out_dir = 'output/corpus3/doc1' ## works # out_dir = 'output/corpus3/doc1/' ## works # out_dir = 'output/corpus3/doc1/doc.txt' ## no error but creates a .../doc.txt./ dir # out_dir = 'output/corpus2/tfidf/' ## fails with "Errno 20" (existing file named "corpus2") # out_dir = 'output/corpus3/tfidf/' ## works # out_dir = 'output/corpus3/a/b/c/d/' ## works # Uncomment these to run "Method 2": #import os, errno #try: # os.makedirs(out_dir) #except OSError as e: # if e.errno != errno.EEXIST: # raise # ----------------------------------------------------------------------------
결론: 제 생각에는 "방법 2"가 더 강력합니다.
[1] 디렉토리가 없으면 어떻게 생성합니까?
[2] https://docs.python.org/3/library/os.html#os.makedirs
Victoria Stuart저는 os.path.exists()
. 여기 에 디렉토리가 존재하는지 확인하는 데 사용할 수 있는 Python 3 스크립트가 있습니다. 디렉토리가 존재하지 않으면 생성하고, 존재하는 경우 삭제합니다(원하는 경우).
사용자에게 디렉토리를 입력하라는 메시지가 표시되며 쉽게 수정할 수 있습니다.
Michael Strobel이 명령을 사용하여 dir을 확인하고 생성하십시오.
if not os.path.isdir(test_img_dir): os.mkdir(test_img_dir)
Manivannan Murugavel-p
옵션과 함께 mkdir
명령을 지원하는 시스템에서 실행 중인 경우 하위 프로세스 모듈을 사용하지 않는 이유는 무엇입니까? 파이썬 2.7 및 파이썬 3.6에서 작동
from subprocess import call call(['mkdir', '-p', 'path1/path2/path3'])
대부분의 시스템에서 트릭을 수행해야 합니다.
이식성이 중요하지 않은 상황(예: docker 사용)에서 솔루션은 깨끗한 2줄입니다. 또한 디렉토리가 존재하는지 여부를 확인하기 위해 논리를 추가할 필요가 없습니다. 마지막으로 부작용 없이 재실행하는 것이 안전합니다.
오류 처리가 필요한 경우:
from subprocess import check_call try: check_call(['mkdir', '-p', 'path1/path2/path3']) except: handle...
Geoff Paul BremnerHeikki Toivonen 과 ABB 의 답변을 보고 이 변형에 대해 생각했습니다.
import os import errno def make_sure_path_exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST or not os.path.isdir(path): raise
alissonmuller디렉토리를 생성하기 전에 전체 경로를 설정해야 합니다.
import os,sys,inspect import pathlib currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) your_folder = currentdir + "/" + "your_folder" if not os.path.exists(your_folder): pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
이것은 저에게 효과가 있으며 바라건대 당신에게도 효과가 있을 것입니다
Hussam Kurdos.listdir
을 사용할 수 있습니다.
import os if 'dirName' in os.listdir('parentFolderPath') print('Directory Exists')
iPhynx프로그램/프로젝트의 진입점에서 create_dir()
함수를 호출합니다.
import os def create_dir(directory): if not os.path.exists(directory): print('Creating Directory '+directory) os.makedirs(directory) create_dir('Project directory')
Steffi Keran Rani J다음을 고려한다면:
os.path.isdir('/tmp/dirname')
디렉토리(경로)가 존재하고 디렉토리임을 의미합니다. 그래서 나를 위해이 방법은 내가 필요로하는 것을 수행합니다. 따라서 폴더(파일이 아님)이고 존재하는지 확인할 수 있습니다.
Ralph Schwerdtfastcore
확장자를 사용하여 1개의 명령으로 파일과 모든 상위 디렉토리를 생성할 수 있습니다 path.mk_write(data)
from fastcore.utils import Path Path('/dir/to/file.txt').mk_write('Hello World')
fastcore 문서 에서 더 보기
korakot변수 경로에 파일을 쓰는 경우 파일 경로에서 이것을 사용하여 상위 디렉토리가 생성되었는지 확인할 수 있습니다.
from pathlib import Path path_to_file = Path("zero/or/more/directories/file.ext") parent_directory_of_file = path_to_file.parent parent_directory_of_file.mkdir(parents=True, exist_ok=True)
path_to_file
이 file.ext
경우에도 작동합니다(0 디렉토리 깊이).
pathlib.PurePath.parent 및 pathlib.Path.mkdir을 참조하십시오.
Dominykas Mostauskisimport os if os.path.isfile(filename): print "file exists" else: "Your code here"
여기에서 코드가 있는 곳은 (터치) 명령을 사용합니다.
파일이 있는지 확인하고 파일이 없으면 생성합니다.
Evil ExistsLinux에서는 한 줄에 디렉터리를 만들 수 있습니다.
import os os.system("mkdir -p {0}".format('mydir'))
Sergiy Maksymenko출처 : 여기를 클릭하세요
출처 : http:www.stackoverflow.com/questions/273192/how-can-i-safely-create-a-nested-directory-in-python